blob: e14e4eb1175871f2cca0e59ff5098bfae308abc6 [file] [log] [blame]
ethannicholasb3058bd2016-07-01 08:22:01 -07001/*
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 */
Ethan Nicholasbcf35f82017-03-30 18:42:48 +00007
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/SkSLSPIRVCodeGenerator.h"
Ethan Nicholas9bd301d2017-03-31 16:04:34 +00009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/GLSL.std.450.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070011
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/sksl/SkSLCompiler.h"
Brian Osman00185012021-02-04 16:07:11 -050013#include "src/sksl/SkSLOperators.h"
John Stiles4d6310a2021-01-26 19:58:22 -050014#include "src/sksl/ir/SkSLBlock.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050015#include "src/sksl/ir/SkSLExpressionStatement.h"
16#include "src/sksl/ir/SkSLExtension.h"
17#include "src/sksl/ir/SkSLIndexExpression.h"
18#include "src/sksl/ir/SkSLVariableReference.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070019
Ethan Nicholas0be34802019-08-15 12:36:58 -040020#ifdef SK_VULKAN
21#include "src/gpu/vk/GrVkCaps.h"
22#endif
23
John Stilescd806892021-01-06 13:33:31 -050024#define kLast_Capability SpvCapabilityMultiViewport
25
ethannicholasb3058bd2016-07-01 08:22:01 -070026namespace SkSL {
27
ethannicholasb3058bd2016-07-01 08:22:01 -070028static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
29
30void SPIRVCodeGenerator::setupIntrinsics() {
John Stilesaaac4e42021-05-06 14:08:28 -040031#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, GLSLstd450 ## x, \
32 GLSLstd450 ## x, GLSLstd450 ## x, GLSLstd450 ## x)
33#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, \
34 GLSLstd450 ## ifFloat, \
35 GLSLstd450 ## ifInt, \
36 GLSLstd450 ## ifUInt, \
ethannicholasb3058bd2016-07-01 08:22:01 -070037 SpvOpUndef)
John Stilesaaac4e42021-05-06 14:08:28 -040038#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicOpcodeKind, \
39 SpvOp ## x, SpvOp ## x, SpvOp ## x, SpvOp ## x)
40#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicOpcodeKind, k ## x ## _SpecialIntrinsic, \
41 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
ethannicholasb3058bd2016-07-01 08:22:01 -070042 k ## x ## _SpecialIntrinsic)
John Stilesaaac4e42021-05-06 14:08:28 -040043 fIntrinsicMap[k_round_IntrinsicKind] = ALL_GLSL(Round);
44 fIntrinsicMap[k_roundEven_IntrinsicKind] = ALL_GLSL(RoundEven);
45 fIntrinsicMap[k_trunc_IntrinsicKind] = ALL_GLSL(Trunc);
46 fIntrinsicMap[k_abs_IntrinsicKind] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
47 fIntrinsicMap[k_sign_IntrinsicKind] = BY_TYPE_GLSL(FSign, SSign, SSign);
48 fIntrinsicMap[k_floor_IntrinsicKind] = ALL_GLSL(Floor);
49 fIntrinsicMap[k_ceil_IntrinsicKind] = ALL_GLSL(Ceil);
50 fIntrinsicMap[k_fract_IntrinsicKind] = ALL_GLSL(Fract);
51 fIntrinsicMap[k_radians_IntrinsicKind] = ALL_GLSL(Radians);
52 fIntrinsicMap[k_degrees_IntrinsicKind] = ALL_GLSL(Degrees);
53 fIntrinsicMap[k_sin_IntrinsicKind] = ALL_GLSL(Sin);
54 fIntrinsicMap[k_cos_IntrinsicKind] = ALL_GLSL(Cos);
55 fIntrinsicMap[k_tan_IntrinsicKind] = ALL_GLSL(Tan);
56 fIntrinsicMap[k_asin_IntrinsicKind] = ALL_GLSL(Asin);
57 fIntrinsicMap[k_acos_IntrinsicKind] = ALL_GLSL(Acos);
58 fIntrinsicMap[k_atan_IntrinsicKind] = SPECIAL(Atan);
59 fIntrinsicMap[k_sinh_IntrinsicKind] = ALL_GLSL(Sinh);
60 fIntrinsicMap[k_cosh_IntrinsicKind] = ALL_GLSL(Cosh);
61 fIntrinsicMap[k_tanh_IntrinsicKind] = ALL_GLSL(Tanh);
62 fIntrinsicMap[k_asinh_IntrinsicKind] = ALL_GLSL(Asinh);
63 fIntrinsicMap[k_acosh_IntrinsicKind] = ALL_GLSL(Acosh);
64 fIntrinsicMap[k_atanh_IntrinsicKind] = ALL_GLSL(Atanh);
65 fIntrinsicMap[k_pow_IntrinsicKind] = ALL_GLSL(Pow);
66 fIntrinsicMap[k_exp_IntrinsicKind] = ALL_GLSL(Exp);
67 fIntrinsicMap[k_log_IntrinsicKind] = ALL_GLSL(Log);
68 fIntrinsicMap[k_exp2_IntrinsicKind] = ALL_GLSL(Exp2);
69 fIntrinsicMap[k_log2_IntrinsicKind] = ALL_GLSL(Log2);
70 fIntrinsicMap[k_sqrt_IntrinsicKind] = ALL_GLSL(Sqrt);
71 fIntrinsicMap[k_inverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
72 fIntrinsicMap[k_outerProduct_IntrinsicKind] = ALL_SPIRV(OuterProduct);
73 fIntrinsicMap[k_transpose_IntrinsicKind] = ALL_SPIRV(Transpose);
74 fIntrinsicMap[k_isinf_IntrinsicKind] = ALL_SPIRV(IsInf);
75 fIntrinsicMap[k_isnan_IntrinsicKind] = ALL_SPIRV(IsNan);
76 fIntrinsicMap[k_inversesqrt_IntrinsicKind] = ALL_GLSL(InverseSqrt);
77 fIntrinsicMap[k_determinant_IntrinsicKind] = ALL_GLSL(Determinant);
78 fIntrinsicMap[k_matrixCompMult_IntrinsicKind] = SPECIAL(MatrixCompMult);
79 fIntrinsicMap[k_matrixInverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
80 fIntrinsicMap[k_mod_IntrinsicKind] = SPECIAL(Mod);
81 fIntrinsicMap[k_modf_IntrinsicKind] = ALL_GLSL(Modf);
82 fIntrinsicMap[k_min_IntrinsicKind] = SPECIAL(Min);
83 fIntrinsicMap[k_max_IntrinsicKind] = SPECIAL(Max);
84 fIntrinsicMap[k_clamp_IntrinsicKind] = SPECIAL(Clamp);
85 fIntrinsicMap[k_saturate_IntrinsicKind] = SPECIAL(Saturate);
86 fIntrinsicMap[k_dot_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
87 SpvOpDot, SpvOpUndef, SpvOpUndef, SpvOpUndef);
88 fIntrinsicMap[k_mix_IntrinsicKind] = SPECIAL(Mix);
89 fIntrinsicMap[k_step_IntrinsicKind] = SPECIAL(Step);
90 fIntrinsicMap[k_smoothstep_IntrinsicKind] = SPECIAL(SmoothStep);
91 fIntrinsicMap[k_fma_IntrinsicKind] = ALL_GLSL(Fma);
92 fIntrinsicMap[k_frexp_IntrinsicKind] = ALL_GLSL(Frexp);
93 fIntrinsicMap[k_ldexp_IntrinsicKind] = ALL_GLSL(Ldexp);
ethannicholasb3058bd2016-07-01 08:22:01 -070094
John Stilesaaac4e42021-05-06 14:08:28 -040095#define PACK(type) fIntrinsicMap[k_pack##type##_IntrinsicKind] = ALL_GLSL(Pack##type); \
96 fIntrinsicMap[k_unpack##type##_IntrinsicKind] = ALL_GLSL(Unpack##type)
ethannicholasb3058bd2016-07-01 08:22:01 -070097 PACK(Snorm4x8);
98 PACK(Unorm4x8);
99 PACK(Snorm2x16);
100 PACK(Unorm2x16);
101 PACK(Half2x16);
102 PACK(Double2x32);
John Stilesaaac4e42021-05-06 14:08:28 -0400103#undef PACK
104 fIntrinsicMap[k_length_IntrinsicKind] = ALL_GLSL(Length);
105 fIntrinsicMap[k_distance_IntrinsicKind] = ALL_GLSL(Distance);
106 fIntrinsicMap[k_cross_IntrinsicKind] = ALL_GLSL(Cross);
107 fIntrinsicMap[k_normalize_IntrinsicKind] = ALL_GLSL(Normalize);
108 fIntrinsicMap[k_faceforward_IntrinsicKind] = ALL_GLSL(FaceForward);
109 fIntrinsicMap[k_reflect_IntrinsicKind] = ALL_GLSL(Reflect);
110 fIntrinsicMap[k_refract_IntrinsicKind] = ALL_GLSL(Refract);
111 fIntrinsicMap[k_bitCount_IntrinsicKind] = ALL_SPIRV(BitCount);
112 fIntrinsicMap[k_findLSB_IntrinsicKind] = ALL_GLSL(FindILsb);
113 fIntrinsicMap[k_findMSB_IntrinsicKind] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
114 fIntrinsicMap[k_dFdx_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
115 SpvOpDPdx, SpvOpUndef,
116 SpvOpUndef, SpvOpUndef);
117 fIntrinsicMap[k_dFdy_IntrinsicKind] = SPECIAL(DFdy);
118 fIntrinsicMap[k_fwidth_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
119 SpvOpFwidth, SpvOpUndef,
120 SpvOpUndef, SpvOpUndef);
121 fIntrinsicMap[k_makeSampler2D_IntrinsicKind] = SPECIAL(SampledImage);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400122
John Stilesaaac4e42021-05-06 14:08:28 -0400123 fIntrinsicMap[k_sample_IntrinsicKind] = SPECIAL(Texture);
124 fIntrinsicMap[k_subpassLoad_IntrinsicKind] = SPECIAL(SubpassLoad);
Greg Daniel64773e62016-11-22 09:44:03 -0500125
John Stilesaaac4e42021-05-06 14:08:28 -0400126 fIntrinsicMap[k_floatBitsToInt_IntrinsicKind] = ALL_SPIRV(Bitcast);
127 fIntrinsicMap[k_floatBitsToUint_IntrinsicKind] = ALL_SPIRV(Bitcast);
128 fIntrinsicMap[k_intBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
129 fIntrinsicMap[k_uintBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
John Stilescc9ff002020-12-09 18:39:41 -0500130
John Stilesaaac4e42021-05-06 14:08:28 -0400131 fIntrinsicMap[k_any_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Brian Osman540c13a2020-11-24 16:55:34 -0500132 SpvOpUndef, SpvOpUndef,
John Stilesaaac4e42021-05-06 14:08:28 -0400133 SpvOpUndef, SpvOpAny);
134 fIntrinsicMap[k_all_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
135 SpvOpUndef, SpvOpUndef,
136 SpvOpUndef, SpvOpAll);
137 fIntrinsicMap[k_not_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
138 SpvOpUndef, SpvOpUndef, SpvOpUndef,
Brian Osman540c13a2020-11-24 16:55:34 -0500139 SpvOpLogicalNot);
John Stilesaaac4e42021-05-06 14:08:28 -0400140 fIntrinsicMap[k_equal_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400141 SpvOpFOrdEqual, SpvOpIEqual,
142 SpvOpIEqual, SpvOpLogicalEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400143 fIntrinsicMap[k_notEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400144 SpvOpFOrdNotEqual, SpvOpINotEqual,
145 SpvOpINotEqual,
146 SpvOpLogicalNotEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400147 fIntrinsicMap[k_lessThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
148 SpvOpFOrdLessThan,
149 SpvOpSLessThan,
150 SpvOpULessThan,
151 SpvOpUndef);
152 fIntrinsicMap[k_lessThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
153 SpvOpFOrdLessThanEqual,
154 SpvOpSLessThanEqual,
155 SpvOpULessThanEqual,
156 SpvOpUndef);
157 fIntrinsicMap[k_greaterThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
158 SpvOpFOrdGreaterThan,
159 SpvOpSGreaterThan,
160 SpvOpUGreaterThan,
161 SpvOpUndef);
162 fIntrinsicMap[k_greaterThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
163 SpvOpFOrdGreaterThanEqual,
164 SpvOpSGreaterThanEqual,
165 SpvOpUGreaterThanEqual,
166 SpvOpUndef);
167 fIntrinsicMap[k_EmitVertex_IntrinsicKind] = ALL_SPIRV(EmitVertex);
168 fIntrinsicMap[k_EndPrimitive_IntrinsicKind] = ALL_SPIRV(EndPrimitive);
ethannicholasb3058bd2016-07-01 08:22:01 -0700169// interpolateAt* not yet supported...
170}
171
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400172void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700173 out.write((const char*) &word, sizeof(word));
ethannicholasb3058bd2016-07-01 08:22:01 -0700174}
175
ethannicholasd598f792016-07-25 10:08:54 -0700176static bool is_float(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500177 return (type.isScalar() || type.isVector() || type.isMatrix()) &&
178 type.componentType().isFloat();
ethannicholasb3058bd2016-07-01 08:22:01 -0700179}
180
ethannicholasd598f792016-07-25 10:08:54 -0700181static bool is_signed(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500182 return type.isEnum() ||
183 ((type.isScalar() || type.isVector()) && type.componentType().isSigned());
ethannicholasb3058bd2016-07-01 08:22:01 -0700184}
185
ethannicholasd598f792016-07-25 10:08:54 -0700186static bool is_unsigned(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500187 return (type.isScalar() || type.isVector()) && type.componentType().isUnsigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700188}
189
ethannicholasd598f792016-07-25 10:08:54 -0700190static bool is_bool(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500191 return (type.isScalar() || type.isVector()) && type.componentType().isBoolean();
ethannicholasb3058bd2016-07-01 08:22:01 -0700192}
193
ethannicholasd598f792016-07-25 10:08:54 -0700194static bool is_out(const Variable& var) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400195 return (var.modifiers().fFlags & Modifiers::kOut_Flag) != 0;
ethannicholasb3058bd2016-07-01 08:22:01 -0700196}
197
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400198void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400199 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
200 SkASSERT(opCode != SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700201 switch (opCode) {
202 case SpvOpReturn: // fall through
203 case SpvOpReturnValue: // fall through
ethannicholas552882f2016-07-07 06:30:48 -0700204 case SpvOpKill: // fall through
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500205 case SpvOpSwitch: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700206 case SpvOpBranch: // fall through
207 case SpvOpBranchConditional:
John Stiles7142e402021-02-23 12:28:18 -0500208 SkASSERT(fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700209 fCurrentBlock = 0;
210 break;
211 case SpvOpConstant: // fall through
212 case SpvOpConstantTrue: // fall through
213 case SpvOpConstantFalse: // fall through
214 case SpvOpConstantComposite: // fall through
215 case SpvOpTypeVoid: // fall through
216 case SpvOpTypeInt: // fall through
217 case SpvOpTypeFloat: // fall through
218 case SpvOpTypeBool: // fall through
219 case SpvOpTypeVector: // fall through
220 case SpvOpTypeMatrix: // fall through
221 case SpvOpTypeArray: // fall through
222 case SpvOpTypePointer: // fall through
223 case SpvOpTypeFunction: // fall through
224 case SpvOpTypeRuntimeArray: // fall through
225 case SpvOpTypeStruct: // fall through
226 case SpvOpTypeImage: // fall through
227 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400228 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700229 case SpvOpVariable: // fall through
230 case SpvOpFunction: // fall through
231 case SpvOpFunctionParameter: // fall through
232 case SpvOpFunctionEnd: // fall through
233 case SpvOpExecutionMode: // fall through
234 case SpvOpMemoryModel: // fall through
235 case SpvOpCapability: // fall through
236 case SpvOpExtInstImport: // fall through
237 case SpvOpEntryPoint: // fall through
238 case SpvOpSource: // fall through
239 case SpvOpSourceExtension: // fall through
240 case SpvOpName: // fall through
241 case SpvOpMemberName: // fall through
242 case SpvOpDecorate: // fall through
243 case SpvOpMemberDecorate:
244 break;
245 default:
John Stilesf3a28db2021-03-10 23:00:47 -0500246 // We may find ourselves with dead code--instructions that don't have an associated
247 // block. This should be a rare event, but if it happens, synthesize a label; this is
248 // necessary to satisfy the validator.
249 if (fCurrentBlock == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400250 this->writeLabel(this->nextId(nullptr), out);
John Stiles7142e402021-02-23 12:28:18 -0500251 }
John Stiles453f1432021-02-25 16:58:04 -0500252 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700253 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700254 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700255}
256
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400257void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500258 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700259 fCurrentBlock = label;
260 this->writeInstruction(SpvOpLabel, label, out);
261}
262
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400263void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700264 this->writeOpCode(opCode, 1, out);
265}
266
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400267void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700268 this->writeOpCode(opCode, 2, out);
269 this->writeWord(word1, out);
270}
271
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700272void SPIRVCodeGenerator::writeString(const char* string, size_t length, OutputStream& out) {
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400273 out.write(string, length);
ethannicholasb3058bd2016-07-01 08:22:01 -0700274 switch (length % 4) {
275 case 1:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500276 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400277 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700278 case 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500279 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400280 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700281 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500282 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700283 break;
284 default:
285 this->writeWord(0, out);
286 }
287}
288
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700289void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, StringFragment string, OutputStream& out) {
290 this->writeOpCode(opCode, 1 + (string.fLength + 4) / 4, out);
291 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700292}
293
294
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700295void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, StringFragment string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400296 OutputStream& out) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700297 this->writeOpCode(opCode, 2 + (string.fLength + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700298 this->writeWord(word1, out);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700299 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700300}
301
Greg Daniel64773e62016-11-22 09:44:03 -0500302void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700303 StringFragment string, OutputStream& out) {
304 this->writeOpCode(opCode, 3 + (string.fLength + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700305 this->writeWord(word1, out);
306 this->writeWord(word2, out);
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700307 this->writeString(string.fChars, string.fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700308}
309
Greg Daniel64773e62016-11-22 09:44:03 -0500310void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400311 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700312 this->writeOpCode(opCode, 3, out);
313 this->writeWord(word1, out);
314 this->writeWord(word2, out);
315}
316
Greg Daniel64773e62016-11-22 09:44:03 -0500317void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400318 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700319 this->writeOpCode(opCode, 4, out);
320 this->writeWord(word1, out);
321 this->writeWord(word2, out);
322 this->writeWord(word3, out);
323}
324
Greg Daniel64773e62016-11-22 09:44:03 -0500325void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400326 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700327 this->writeOpCode(opCode, 5, out);
328 this->writeWord(word1, out);
329 this->writeWord(word2, out);
330 this->writeWord(word3, out);
331 this->writeWord(word4, out);
332}
333
Greg Daniel64773e62016-11-22 09:44:03 -0500334void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
335 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400336 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700337 this->writeOpCode(opCode, 6, out);
338 this->writeWord(word1, out);
339 this->writeWord(word2, out);
340 this->writeWord(word3, out);
341 this->writeWord(word4, out);
342 this->writeWord(word5, out);
343}
344
Greg Daniel64773e62016-11-22 09:44:03 -0500345void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700346 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400347 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700348 this->writeOpCode(opCode, 7, out);
349 this->writeWord(word1, out);
350 this->writeWord(word2, out);
351 this->writeWord(word3, out);
352 this->writeWord(word4, out);
353 this->writeWord(word5, out);
354 this->writeWord(word6, out);
355}
356
Greg Daniel64773e62016-11-22 09:44:03 -0500357void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700358 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400359 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700360 this->writeOpCode(opCode, 8, out);
361 this->writeWord(word1, out);
362 this->writeWord(word2, out);
363 this->writeWord(word3, out);
364 this->writeWord(word4, out);
365 this->writeWord(word5, out);
366 this->writeWord(word6, out);
367 this->writeWord(word7, out);
368}
369
Greg Daniel64773e62016-11-22 09:44:03 -0500370void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700371 int32_t word3, int32_t word4, int32_t word5,
372 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400373 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700374 this->writeOpCode(opCode, 9, out);
375 this->writeWord(word1, out);
376 this->writeWord(word2, out);
377 this->writeWord(word3, out);
378 this->writeWord(word4, out);
379 this->writeWord(word5, out);
380 this->writeWord(word6, out);
381 this->writeWord(word7, out);
382 this->writeWord(word8, out);
383}
384
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400385void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700386 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
387 if (fCapabilities & bit) {
388 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
389 }
390 }
John Stiles270cec22021-02-17 12:59:36 -0500391 if (fProgram.fConfig->fKind == ProgramKind::kGeometry) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400392 this->writeInstruction(SpvOpCapability, SpvCapabilityGeometry, out);
393 }
Ethan Nicholas81d15112018-07-13 12:48:50 -0400394 else {
395 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
396 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700397}
398
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400399SpvId SPIRVCodeGenerator::nextId(const Type* type) {
400 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
401 ? Precision::kRelaxed
402 : Precision::kDefault);
403}
404
405SpvId SPIRVCodeGenerator::nextId(Precision precision) {
406 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
407 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
408 fDecorationBuffer);
409 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700410 return fIdCount++;
411}
412
Ethan Nicholas19671772016-11-28 16:30:17 -0500413void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
414 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400415 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700416 // go ahead and write all of the field types, so we don't inadvertently write them while we're
417 // in the middle of writing the struct instruction
418 std::vector<SpvId> types;
419 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500420 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700421 }
422 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
423 this->writeWord(resultId, fConstantBuffer);
424 for (SpvId id : types) {
425 this->writeWord(id, fConstantBuffer);
426 }
427 size_t offset = 0;
428 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400429 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500430 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
John Stiles0023c0c2020-11-16 13:32:18 -0500431 fErrors.error(type.fOffset, "type '" + field.fType->name() + "' is not permitted here");
432 return;
433 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400434 size_t size = memoryLayout.size(*field.fType);
435 size_t alignment = memoryLayout.alignment(*field.fType);
436 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500437 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500438 if (fieldLayout.fOffset < (int) offset) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700439 fErrors.error(type.fOffset,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400440 "offset of field '" + field.fName + "' must be at "
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500441 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500442 }
443 if (fieldLayout.fOffset % alignment) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700444 fErrors.error(type.fOffset,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400445 "offset of field '" + field.fName + "' must be a multiple"
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500446 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500447 }
448 offset = fieldLayout.fOffset;
449 } else {
450 size_t mod = offset % alignment;
451 if (mod) {
452 offset += alignment - mod;
453 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700454 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400455 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500456 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400457 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500458 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700459 (SpvId) offset, fDecorationBuffer);
460 }
John Stiles9aeed132020-11-24 17:36:06 -0500461 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500462 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700463 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500464 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400465 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800466 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700467 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400468 if (!field.fType->highPrecision()) {
469 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
470 SpvDecorationRelaxedPrecision, fDecorationBuffer);
471 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700472 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500473 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700474 offset += alignment - offset % alignment;
475 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700476 }
477}
478
Ethan Nicholase2c49992020-10-05 11:49:11 -0400479const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500480 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500481 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400482 }
John Stiles4c151702021-02-09 18:31:34 -0500483 if (type.isSigned() || type.isEnum()) {
John Stiles54e7c052021-01-11 14:22:36 -0500484 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400485 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500486 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500487 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400488 }
John Stiles9aeed132020-11-24 17:36:06 -0500489 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500490 if (type.componentType() == *fContext.fTypes.fHalf) {
491 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400492 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400493 if (type.componentType() == *fContext.fTypes.fShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500494 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400495 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400496 if (type.componentType() == *fContext.fTypes.fUShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500497 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400498 }
499 }
500 return type;
501}
502
ethannicholasb3058bd2016-07-01 08:22:01 -0700503SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800504 return this->getType(type, fDefaultLayout);
505}
506
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400507SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400508 const Type& type = this->getActualType(rawType);
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400509 String key = type.name();
John Stilesc0c51062020-12-03 17:16:29 -0500510 if (type.isStruct() || type.isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400511 key += to_string((int)layout.fStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500512#ifdef SK_DEBUG
513 SkASSERT(layout.fStd == MemoryLayout::Standard::k140_Standard ||
514 layout.fStd == MemoryLayout::Standard::k430_Standard);
515 MemoryLayout::Standard otherStd = layout.fStd == MemoryLayout::Standard::k140_Standard
516 ? MemoryLayout::Standard::k430_Standard
517 : MemoryLayout::Standard::k140_Standard;
518 String otherKey = type.name() + to_string((int)otherStd);
519 SkASSERT(fTypeMap.find(otherKey) == fTypeMap.end());
520#endif
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400521 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800522 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700523 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400524 SpvId result = this->nextId(nullptr);
Ethan Nicholase6592142020-09-08 10:22:09 -0400525 switch (type.typeKind()) {
526 case Type::TypeKind::kScalar:
John Stiles4a7dc462020-11-25 11:08:08 -0500527 if (type.isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700528 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500529 } else if (type == *fContext.fTypes.fInt || type == *fContext.fTypes.fShort ||
530 type == *fContext.fTypes.fIntLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700531 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500532 } else if (type == *fContext.fTypes.fUInt || type == *fContext.fTypes.fUShort) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700533 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500534 } else if (type == *fContext.fTypes.fFloat || type == *fContext.fTypes.fHalf ||
535 type == *fContext.fTypes.fFloatLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700536 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700537 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400538 SkASSERT(false);
ethannicholasb3058bd2016-07-01 08:22:01 -0700539 }
540 break;
John Stilesfd41d872020-11-25 22:39:45 -0500541 case Type::TypeKind::kEnum:
542 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
543 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400544 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500545 this->writeInstruction(SpvOpTypeVector, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800546 this->getType(type.componentType(), layout),
ethannicholasb3058bd2016-07-01 08:22:01 -0700547 type.columns(), fConstantBuffer);
548 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400549 case Type::TypeKind::kMatrix:
John Stiles51d33982021-03-08 09:18:07 -0500550 this->writeInstruction(
551 SpvOpTypeMatrix,
552 result,
553 this->getType(IndexExpression::IndexType(fContext, type), layout),
554 type.columns(),
555 fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700556 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400557 case Type::TypeKind::kStruct:
ethannicholas8ac838d2016-11-22 08:39:36 -0800558 this->writeStruct(type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700559 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400560 case Type::TypeKind::kArray: {
John Stiles21f5f452020-11-30 09:57:59 -0500561 if (!MemoryLayout::LayoutIsSupported(type)) {
562 fErrors.error(type.fOffset, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400563 return this->nextId(nullptr);
John Stiles21f5f452020-11-30 09:57:59 -0500564 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700565 if (type.columns() > 0) {
John Stilesb5db4822021-01-21 13:04:40 -0500566 SpvId typeId = this->getType(type.componentType(), layout);
John Stiles9ce80f72021-03-11 22:35:19 -0500567 IntLiteral countLiteral(/*offset=*/-1, type.columns(),
568 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -0500569 SpvId countId = this->writeIntLiteral(countLiteral);
570 this->writeInstruction(SpvOpTypeArray, result, typeId, countId,
571 fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500572 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400573 (int32_t) layout.stride(type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800574 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700575 } else {
John Stiles5570c512020-11-19 17:58:07 -0500576 // We shouldn't have any runtime-sized arrays right now
577 fErrors.error(type.fOffset, "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500578 this->writeInstruction(SpvOpTypeRuntimeArray, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800579 this->getType(type.componentType(), layout),
580 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400581 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
582 (int32_t) layout.stride(type),
583 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700584 }
585 break;
586 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400587 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500588 SpvId image = result;
589 if (SpvDimSubpassData != type.dimensions()) {
Stephen White792e2302019-08-09 13:33:51 -0400590 image = this->getType(type.textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500591 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400592 if (SpvDimBuffer == type.dimensions()) {
593 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
594 }
Greg Daniel64773e62016-11-22 09:44:03 -0500595 if (SpvDimSubpassData != type.dimensions()) {
596 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
597 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700598 break;
599 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400600 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400601 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
602 break;
603 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400604 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400605 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500606 this->getType(*fContext.fTypes.fFloat, layout),
John Stilesc0c51062020-12-03 17:16:29 -0500607 type.dimensions(), type.isDepth(), type.isArrayedTexture(),
Stephen White792e2302019-08-09 13:33:51 -0400608 type.isMultisampled(), type.isSampled() ? 1 : 2,
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400609 SpvImageFormatUnknown, fConstantBuffer);
610 fImageTypeMap[key] = result;
611 break;
612 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700613 default:
John Stiles2558c462021-03-16 17:49:20 -0400614 if (type.isVoid()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700615 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
616 } else {
John Stileseada7bc2021-02-02 16:29:32 -0500617 SkDEBUGFAILF("invalid type: %s", type.description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700618 }
619 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800620 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700621 return result;
622 }
623 return entry->second;
624}
625
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400626SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400627 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400628 this->getType(type);
629 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400630 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400631 return fImageTypeMap[key];
632}
633
ethannicholasd598f792016-07-25 10:08:54 -0700634SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400635 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400636 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400637 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400638 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700639 key += separator;
640 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400641 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700642 }
643 key += ")";
644 auto entry = fTypeMap.find(key);
645 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400646 SpvId result = this->nextId(nullptr);
Ethan Nicholased84b732020-10-08 11:45:44 -0400647 int32_t length = 3 + (int32_t) parameters.size();
648 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700649 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400650 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500651 // glslang seems to treat all function arguments as pointers whether they need to be or
652 // not. I was initially puzzled by this until I ran bizarre failures with certain
653 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700654 // failure case:
655 //
656 // void sphere(float x) {
657 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500658 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700659 // void map() {
660 // sphere(1.0);
661 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500662 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700663 // void main() {
664 // for (int i = 0; i < 1; i++) {
665 // map();
666 // }
667 // }
668 //
Greg Daniel64773e62016-11-22 09:44:03 -0500669 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
670 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700671 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
672 // the spec makes this make sense.
673// if (is_out(function->fParameters[i])) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400674 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
ethannicholasb3058bd2016-07-01 08:22:01 -0700675 SpvStorageClassFunction));
676// } else {
ethannicholasd598f792016-07-25 10:08:54 -0700677// parameterTypes.push_back(this->getType(function.fParameters[i]->fType));
ethannicholasb3058bd2016-07-01 08:22:01 -0700678// }
679 }
680 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
681 this->writeWord(result, fConstantBuffer);
682 this->writeWord(returnType, fConstantBuffer);
683 for (SpvId id : parameterTypes) {
684 this->writeWord(id, fConstantBuffer);
685 }
686 fTypeMap[key] = result;
687 return result;
688 }
689 return entry->second;
690}
691
ethannicholas8ac838d2016-11-22 08:39:36 -0800692SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
693 return this->getPointerType(type, fDefaultLayout, storageClass);
694}
695
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400696SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700697 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400698 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500699 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700700 auto entry = fTypeMap.find(key);
701 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400702 SpvId result = this->nextId(nullptr);
Greg Daniel64773e62016-11-22 09:44:03 -0500703 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700704 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700705 fTypeMap[key] = result;
706 return result;
707 }
708 return entry->second;
709}
710
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400711SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400712 switch (expr.kind()) {
713 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400714 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400715 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400716 return this->writeBoolLiteral(expr.as<BoolLiteral>());
John Stiles7384b372021-04-01 13:48:15 -0400717 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400718 case Expression::Kind::kConstructorStruct:
719 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
John Stilese1182782021-03-30 22:09:37 -0400720 case Expression::Kind::kConstructorDiagonalMatrix:
721 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
John Stiles5abb9e12021-04-06 13:47:19 -0400722 case Expression::Kind::kConstructorMatrixResize:
723 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
John Stilesfd7252f2021-04-04 22:24:40 -0400724 case Expression::Kind::kConstructorScalarCast:
725 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
John Stiles2938eea2021-04-01 18:58:25 -0400726 case Expression::Kind::kConstructorSplat:
727 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
John Stiles8cad6372021-04-07 12:31:13 -0400728 case Expression::Kind::kConstructorCompound:
729 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
730 case Expression::Kind::kConstructorCompoundCast:
731 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400732 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400733 return this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400734 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400735 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400736 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400737 return this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400738 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400739 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400740 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400741 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400742 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400743 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400744 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400745 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400746 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400747 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400748 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400749 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400750 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400751 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700752 default:
John Stileseada7bc2021-02-02 16:29:32 -0500753 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500754 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700755 }
756 return -1;
757}
758
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400759SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400760 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -0400761 auto intrinsic = fIntrinsicMap.find(function.intrinsicKind());
John Stiles93e661a2020-12-08 16:17:00 -0500762 if (intrinsic == fIntrinsicMap.end()) {
763 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
764 return -1;
765 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700766 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500767 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400768 if (arguments.size() > 0) {
769 const Type& type = arguments[0]->type();
John Stilesaaac4e42021-05-06 14:08:28 -0400770 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicOpcodeKind ||
771 is_float(fContext, type)) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400772 intrinsicId = std::get<1>(intrinsic->second);
773 } else if (is_signed(fContext, type)) {
774 intrinsicId = std::get<2>(intrinsic->second);
775 } else if (is_unsigned(fContext, type)) {
776 intrinsicId = std::get<3>(intrinsic->second);
777 } else if (is_bool(fContext, type)) {
778 intrinsicId = std::get<4>(intrinsic->second);
779 } else {
780 intrinsicId = std::get<1>(intrinsic->second);
781 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700782 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400783 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700784 }
785 switch (std::get<0>(intrinsic->second)) {
John Stilesaaac4e42021-05-06 14:08:28 -0400786 case kGLSL_STD_450_IntrinsicOpcodeKind: {
Ethan Nicholas7f015882021-03-23 14:16:52 -0400787 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400788 std::vector<SpvId> argumentIds;
789 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400790 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500791 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400792 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400793 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400794 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400795 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700796 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400797 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400798 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700799 this->writeWord(result, out);
800 this->writeWord(fGLSLExtendedInstructions, out);
801 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400802 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700803 this->writeWord(id, out);
804 }
805 return result;
806 }
John Stilesaaac4e42021-05-06 14:08:28 -0400807 case kSPIRV_IntrinsicOpcodeKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500808 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500809 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500810 intrinsicId = SpvOpFMul;
811 }
Ethan Nicholas7f015882021-03-23 14:16:52 -0400812 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400813 std::vector<SpvId> argumentIds;
814 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400815 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500816 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400817 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400818 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400819 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400820 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700821 }
John Stiles2558c462021-03-16 17:49:20 -0400822 if (!c.type().isVoid()) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400823 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400824 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400825 this->writeWord(result, out);
826 } else {
827 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
828 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400829 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700830 this->writeWord(id, out);
831 }
832 return result;
833 }
John Stilesaaac4e42021-05-06 14:08:28 -0400834 case kSpecial_IntrinsicOpcodeKind:
ethannicholasb3058bd2016-07-01 08:22:01 -0700835 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
836 default:
John Stiles93e661a2020-12-08 16:17:00 -0500837 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
838 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700839 }
840}
841
John Stiles8e3b6be2020-10-13 11:14:08 -0400842std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500843 int vectorSize = 0;
844 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500845 if (a->type().isVector()) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500846 if (vectorSize) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400847 SkASSERT(a->type().columns() == vectorSize);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500848 }
849 else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400850 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500851 }
852 }
853 }
854 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400855 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400856 for (const auto& arg : args) {
857 const Type& argType = arg->type();
Robert Phillipsc650cc02021-05-14 14:29:23 +0000858 SpvId raw = this->writeExpression(*arg, out);
John Stiles9aeed132020-11-24 17:36:06 -0500859 if (vectorSize && argType.isScalar()) {
Robert Phillipsc650cc02021-05-14 14:29:23 +0000860 SpvId vector = this->nextId(&arg->type());
861 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
862 this->writeWord(this->getType(argType.toCompound(fContext, vectorSize, 1)), out);
863 this->writeWord(vector, out);
864 for (int i = 0; i < vectorSize; i++) {
865 this->writeWord(raw, out);
866 }
867 result.push_back(vector);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500868 } else {
Robert Phillipsc650cc02021-05-14 14:29:23 +0000869 result.push_back(raw);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500870 }
871 }
872 return result;
873}
874
875void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
876 SpvId signedInst, SpvId unsignedInst,
877 const std::vector<SpvId>& args,
878 OutputStream& out) {
879 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
880 this->writeWord(this->getType(type), out);
881 this->writeWord(id, out);
882 this->writeWord(fGLSLExtendedInstructions, out);
883
884 if (is_float(fContext, type)) {
885 this->writeWord(floatInst, out);
886 } else if (is_signed(fContext, type)) {
887 this->writeWord(signedInst, out);
888 } else if (is_unsigned(fContext, type)) {
889 this->writeWord(unsignedInst, out);
890 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400891 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500892 }
893 for (SpvId a : args) {
894 this->writeWord(a, out);
895 }
896}
897
Greg Daniel64773e62016-11-22 09:44:03 -0500898SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400899 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400900 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400901 const Type& callType = c.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400902 SpvId result = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700903 switch (kind) {
904 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400905 std::vector<SpvId> argumentIds;
906 for (const std::unique_ptr<Expression>& arg : arguments) {
907 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700908 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400909 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400910 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700911 this->writeWord(result, out);
912 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400913 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
914 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700915 this->writeWord(id, out);
916 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400917 break;
918 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400919 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400920 SkASSERT(arguments.size() == 2);
921 SpvId img = this->writeExpression(*arguments[0], out);
922 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400923 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400924 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400925 result,
926 img,
927 sampler,
928 out);
929 break;
930 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400931 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400932 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400933 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400934 args.reserve_back(2);
John Stiles9ce80f72021-03-11 22:35:19 -0500935 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
936 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
John Stiles8cad6372021-04-07 12:31:13 -0400937 ConstructorCompound ctor(/*offset=*/-1, *fContext.fTypes.fInt2, std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400938 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400939 if (arguments.size() == 1) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400940 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400941 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400942 result,
943 img,
944 coords,
945 out);
946 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400947 SkASSERT(arguments.size() == 2);
948 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400949 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400950 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400951 result,
952 img,
953 coords,
954 SpvImageOperandsSampleMask,
955 sample,
956 out);
957 }
958 break;
959 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700960 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500961 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400962 const Type& arg1Type = arguments[1]->type();
963 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500964 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -0500965 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500966 op = SpvOpImageSampleProjImplicitLod;
967 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500968 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500969 }
970 break;
971 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -0500972 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500973 op = SpvOpImageSampleProjImplicitLod;
974 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500975 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500976 }
977 break;
978 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -0500979 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500980 op = SpvOpImageSampleProjImplicitLod;
981 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500982 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500983 }
984 break;
985 case SpvDimCube: // fall through
986 case SpvDimRect: // fall through
987 case SpvDimBuffer: // fall through
988 case SpvDimSubpassData:
989 break;
990 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400991 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400992 SpvId sampler = this->writeExpression(*arguments[0], out);
993 SpvId uv = this->writeExpression(*arguments[1], out);
994 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500995 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -0700996 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400997 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -0700998 out);
999 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001000 SkASSERT(arguments.size() == 2);
John Stiles270cec22021-02-17 12:59:36 -05001001 if (fProgram.fConfig->fSettings.fSharpenTextures) {
John Stiles9ce80f72021-03-11 22:35:19 -05001002 FloatLiteral lodBias(/*offset=*/-1, /*value=*/-0.5,
1003 fContext.fTypes.fFloat.get());
Brian Osman8a83ca42018-02-12 14:32:17 -05001004 this->writeInstruction(op, type, result, sampler, uv,
1005 SpvImageOperandsBiasMask,
1006 this->writeFloatLiteral(lodBias),
1007 out);
1008 } else {
1009 this->writeInstruction(op, type, result, sampler, uv,
1010 out);
1011 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001012 }
1013 break;
1014 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001015 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001016 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001017 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001018 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001019 SpvOp_ op;
1020 if (is_float(fContext, operandType)) {
1021 op = SpvOpFMod;
1022 } else if (is_signed(fContext, operandType)) {
1023 op = SpvOpSMod;
1024 } else if (is_unsigned(fContext, operandType)) {
1025 op = SpvOpUMod;
1026 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001027 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001028 return 0;
1029 }
1030 this->writeOpCode(op, 5, out);
1031 this->writeWord(this->getType(operandType), out);
1032 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001033 this->writeWord(args[0], out);
1034 this->writeWord(args[1], out);
1035 break;
1036 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001037 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001038 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001039 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001040 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001041 this->writeWord(result, out);
1042 this->writeWord(fn, out);
John Stiles270cec22021-02-17 12:59:36 -05001043 if (fProgram.fConfig->fSettings.fFlipY) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001044 // Flipping Y also negates the Y derivatives.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001045 SpvId flipped = this->nextId(&callType);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001046 this->writeInstruction(SpvOpFNegate, this->getType(callType), flipped, result,
1047 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001048 result = flipped;
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001049 }
1050 break;
1051 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001052 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001053 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001054 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001055 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001056 GLSLstd450UClamp, args, out);
1057 break;
1058 }
1059 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001060 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001061 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001062 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001063 GLSLstd450UMax, args, out);
1064 break;
1065 }
1066 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001067 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001068 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001069 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001070 GLSLstd450UMin, args, out);
1071 break;
1072 }
1073 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001074 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001075 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001076 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001077 SpvOpUndef, args, out);
1078 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001079 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001080 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001081 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001082 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001083 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001084 finalArgs.push_back(arguments[0]->clone());
John Stiles9ce80f72021-03-11 22:35:19 -05001085 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
1086 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001087 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001088 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001089 GLSLstd450UClamp, spvArgs, out);
1090 break;
1091 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001092 case kSmoothStep_SpecialIntrinsic: {
1093 std::vector<SpvId> args = this->vectorize(arguments, out);
1094 SkASSERT(args.size() == 3);
1095 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1096 SpvOpUndef, args, out);
1097 break;
1098 }
1099 case kStep_SpecialIntrinsic: {
1100 std::vector<SpvId> args = this->vectorize(arguments, out);
1101 SkASSERT(args.size() == 2);
1102 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1103 SpvOpUndef, args, out);
1104 break;
1105 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001106 case kMatrixCompMult_SpecialIntrinsic: {
1107 SkASSERT(arguments.size() == 2);
1108 SpvId lhs = this->writeExpression(*arguments[0], out);
1109 SpvId rhs = this->writeExpression(*arguments[1], out);
John Stiles43b593c2021-05-13 22:03:27 -04001110 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
Brian Osmand1b593f2020-12-28 13:00:46 -05001111 break;
1112 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001113 }
1114 return result;
1115}
1116
John Stilesec241542021-02-11 17:50:09 -05001117namespace {
1118struct TempVar {
1119 SpvId spvId;
1120 const Type* type;
1121 std::unique_ptr<SPIRVCodeGenerator::LValue> lvalue;
1122};
1123}
1124
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001125SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001126 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -04001127 if (function.isIntrinsic() && !function.definition()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001128 return this->writeIntrinsicCall(c, out);
1129 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001130 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001131 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001132 if (entry == fFunctionMap.end()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001133 fErrors.error(c.fOffset, "function '" + function.description() + "' is not defined");
1134 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001135 }
John Stilesec241542021-02-11 17:50:09 -05001136 // Temp variables are used to write back out-parameters after the function call is complete.
1137 std::vector<TempVar> tempVars;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001138 std::vector<SpvId> argumentIds;
1139 for (size_t i = 0; i < arguments.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -05001140 // id of temporary variable that we will use to hold this argument, or 0 if it is being
ethannicholasb3058bd2016-07-01 08:22:01 -07001141 // passed directly
1142 SpvId tmpVar;
1143 // if we need a temporary var to store this argument, this is the value to store in the var
1144 SpvId tmpValueId;
Ethan Nicholased84b732020-10-08 11:45:44 -04001145 if (is_out(*function.parameters()[i])) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001146 std::unique_ptr<LValue> lv = this->getLValue(*arguments[i], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001147 SpvId ptr = lv->getPointer();
Ethan Nicholase0707b72021-03-17 11:16:41 -04001148 if (ptr != (SpvId) -1 && lv->isMemoryObjectPointer()) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001149 argumentIds.push_back(ptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001150 continue;
1151 } else {
1152 // lvalue cannot simply be read and written via a pointer (e.g. a swizzle). Need to
1153 // copy it into a temp, call the function, read the value out of the temp, and then
1154 // update the lvalue.
1155 tmpValueId = lv->load(out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001156 tmpVar = this->nextId(nullptr);
John Stilesec241542021-02-11 17:50:09 -05001157 tempVars.push_back(TempVar{tmpVar, &arguments[i]->type(), std::move(lv)});
ethannicholasb3058bd2016-07-01 08:22:01 -07001158 }
1159 } else {
John Stilesec241542021-02-11 17:50:09 -05001160 // See getFunctionType for an explanation of why we're always using pointer parameters.
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001161 tmpValueId = this->writeExpression(*arguments[i], out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001162 tmpVar = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001163 }
Greg Daniel64773e62016-11-22 09:44:03 -05001164 this->writeInstruction(SpvOpVariable,
John Stilesec241542021-02-11 17:50:09 -05001165 this->getPointerType(arguments[i]->type(), SpvStorageClassFunction),
Greg Daniel64773e62016-11-22 09:44:03 -05001166 tmpVar,
ethannicholasb3058bd2016-07-01 08:22:01 -07001167 SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07001168 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001169 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001170 argumentIds.push_back(tmpVar);
ethannicholasb3058bd2016-07-01 08:22:01 -07001171 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001172 SpvId result = this->nextId(nullptr);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001173 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001174 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001175 this->writeWord(result, out);
1176 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001177 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001178 this->writeWord(id, out);
1179 }
John Stilesec241542021-02-11 17:50:09 -05001180 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
1181 for (const TempVar& tempVar : tempVars) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001182 SpvId load = this->nextId(tempVar.type);
John Stilesec241542021-02-11 17:50:09 -05001183 this->writeInstruction(SpvOpLoad, getType(*tempVar.type), load, tempVar.spvId, out);
John Stilesec241542021-02-11 17:50:09 -05001184 tempVar.lvalue->store(load, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001185 }
1186 return result;
1187}
1188
John Stiles2938eea2021-04-01 18:58:25 -04001189SpvId SPIRVCodeGenerator::writeConstantVector(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001190 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001191 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001192
John Stiles9cfaa4f2021-01-06 17:52:00 -05001193 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001194 SPIRVVectorConstant key{this->getType(type),
1195 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001196
John Stiles21a50ec2021-04-06 14:49:36 -04001197 for (int n = 0; n < type.columns(); n++) {
1198 const Expression* expr = c.getConstantSubexpression(n);
1199 if (!expr) {
1200 SkDEBUGFAILF("writeConstantVector: %s not actually constant", c.description().c_str());
1201 return (SpvId)-1;
John Stiles9cfaa4f2021-01-06 17:52:00 -05001202 }
John Stiles21a50ec2021-04-06 14:49:36 -04001203 key.fValueId[n] = this->writeExpression(*expr, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001204 }
John Stilescd806892021-01-06 13:33:31 -05001205
1206 // Check to see if we've already synthesized this vector constant.
1207 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1208 if (newlyCreated) {
1209 // Emit an OpConstantComposite instruction for this constant.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001210 SpvId result = this->nextId(&type);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001211 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001212 this->writeWord(key.fTypeId, fConstantBuffer);
1213 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001214 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001215 this->writeWord(key.fValueId[i], fConstantBuffer);
1216 }
1217 iter->second = result;
1218 }
1219 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001220}
1221
John Stilesb14a8192021-04-05 11:40:46 -04001222SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
1223 const Type& inputType,
1224 const Type& outputType,
1225 OutputStream& out) {
1226 if (outputType.isFloat()) {
1227 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
1228 }
1229 if (outputType.isSigned()) {
1230 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
1231 }
1232 if (outputType.isUnsigned()) {
1233 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
1234 }
1235 if (outputType.isBoolean()) {
1236 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
1237 }
1238
1239 fErrors.error(-1, "unsupported cast: " + inputType.description() +
1240 " to " + outputType.description());
1241 return inputExprId;
1242}
1243
John Stilesfd7252f2021-04-04 22:24:40 -04001244SpvId SPIRVCodeGenerator::writeFloatConstructor(const AnyConstructor& c, OutputStream& out) {
1245 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001246 SkASSERT(c.type().isFloat());
John Stilesfd7252f2021-04-04 22:24:40 -04001247 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001248 SpvId expressionId = this->writeExpression(ctorExpr, out);
1249 return this->castScalarToFloat(expressionId, ctorExpr.type(), c.type(), out);
1250}
1251
1252SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
1253 const Type& outputType, OutputStream& out) {
1254 // Casting a float to float is a no-op.
1255 if (inputType.isFloat()) {
1256 return inputId;
1257 }
1258
1259 // Given the input type, generate the appropriate instruction to cast to float.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001260 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001261 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001262 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
John Stiles9ce80f72021-03-11 22:35:19 -05001263 FloatLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001264 SpvId oneID = this->writeFloatLiteral(one);
John Stiles9ce80f72021-03-11 22:35:19 -05001265 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001266 SpvId zeroID = this->writeFloatLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001267 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1268 inputId, oneID, zeroID, out);
1269 } else if (inputType.isSigned()) {
1270 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
1271 } else if (inputType.isUnsigned()) {
1272 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001273 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001274 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
1275 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001276 }
1277 return result;
1278}
1279
John Stilesfd7252f2021-04-04 22:24:40 -04001280SpvId SPIRVCodeGenerator::writeIntConstructor(const AnyConstructor& c, OutputStream& out) {
1281 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001282 SkASSERT(c.type().isSigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001283 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001284 SpvId expressionId = this->writeExpression(ctorExpr, out);
1285 return this->castScalarToSignedInt(expressionId, ctorExpr.type(), c.type(), out);
1286}
1287
1288SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
1289 const Type& outputType, OutputStream& out) {
1290 // Casting a signed int to signed int is a no-op.
1291 if (inputType.isSigned()) {
1292 return inputId;
1293 }
1294
1295 // Given the input type, generate the appropriate instruction to cast to signed int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001296 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001297 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001298 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
John Stiles54e7c052021-01-11 14:22:36 -05001299 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001300 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001301 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001302 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001303 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1304 inputId, oneID, zeroID, out);
1305 } else if (inputType.isFloat()) {
1306 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
1307 } else if (inputType.isUnsigned()) {
1308 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
1309 } else {
1310 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
1311 inputType.description().c_str());
1312 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001313 }
1314 return result;
1315}
1316
John Stilesfd7252f2021-04-04 22:24:40 -04001317SpvId SPIRVCodeGenerator::writeUIntConstructor(const AnyConstructor& c, OutputStream& out) {
1318 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001319 SkASSERT(c.type().isUnsigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001320 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001321 SpvId expressionId = this->writeExpression(ctorExpr, out);
1322 return this->castScalarToUnsignedInt(expressionId, ctorExpr.type(), c.type(), out);
1323}
1324
1325SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
1326 const Type& outputType, OutputStream& out) {
1327 // Casting an unsigned int to unsigned int is a no-op.
1328 if (inputType.isUnsigned()) {
1329 return inputId;
1330 }
1331
John Stiles48c28842021-01-14 11:05:03 -05001332 // Given the input type, generate the appropriate instruction to cast to unsigned int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001333 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001334 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001335 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
John Stiles54e7c052021-01-11 14:22:36 -05001336 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001337 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001338 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001339 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001340 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1341 inputId, oneID, zeroID, out);
1342 } else if (inputType.isFloat()) {
1343 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
1344 } else if (inputType.isSigned()) {
1345 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001346 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001347 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
1348 inputType.description().c_str());
1349 return (SpvId)-1;
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001350 }
1351 return result;
1352}
1353
John Stilesfd7252f2021-04-04 22:24:40 -04001354SpvId SPIRVCodeGenerator::writeBooleanConstructor(const AnyConstructor& c, OutputStream& out) {
1355 SkASSERT(c.argumentSpan().size() == 1);
John Stilesa60fb172021-01-14 11:06:20 -05001356 SkASSERT(c.type().isBoolean());
John Stilesfd7252f2021-04-04 22:24:40 -04001357 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesa60fb172021-01-14 11:06:20 -05001358 SpvId expressionId = this->writeExpression(ctorExpr, out);
1359 return this->castScalarToBoolean(expressionId, ctorExpr.type(), c.type(), out);
1360}
1361
John Stiles48c28842021-01-14 11:05:03 -05001362SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
1363 const Type& outputType, OutputStream& out) {
1364 // Casting a bool to bool is a no-op.
1365 if (inputType.isBoolean()) {
1366 return inputId;
1367 }
1368
1369 // Given the input type, generate the appropriate instruction to cast to bool.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001370 SpvId result = this->nextId(nullptr);
John Stiles48c28842021-01-14 11:05:03 -05001371 if (inputType.isSigned()) {
1372 // Synthesize a boolean result by comparing the input against a signed zero literal.
1373 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
1374 SpvId zeroID = this->writeIntLiteral(zero);
1375 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1376 inputId, zeroID, out);
1377 } else if (inputType.isUnsigned()) {
1378 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
1379 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
1380 SpvId zeroID = this->writeIntLiteral(zero);
1381 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1382 inputId, zeroID, out);
1383 } else if (inputType.isFloat()) {
1384 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
1385 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
1386 SpvId zeroID = this->writeFloatLiteral(zero);
1387 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
1388 inputId, zeroID, out);
1389 } else {
1390 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
1391 return (SpvId)-1;
1392 }
1393 return result;
1394}
1395
Ethan Nicholas84645e32017-02-09 13:57:14 -05001396void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001397 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05001398 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001399 SpvId zeroId = this->writeFloatLiteral(zero);
1400 std::vector<SpvId> columnIds;
John Stiles392d8292021-04-09 12:14:03 -04001401 columnIds.reserve(type.columns());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001402 for (int column = 0; column < type.columns(); column++) {
1403 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1404 out);
John Stiles392d8292021-04-09 12:14:03 -04001405 this->writeWord(this->getType(type.componentType().toCompound(
1406 fContext, /*columns=*/type.rows(), /*rows=*/1)),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001407 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001408 SpvId columnId = this->nextId(&type);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001409 this->writeWord(columnId, out);
1410 columnIds.push_back(columnId);
John Stiles392d8292021-04-09 12:14:03 -04001411 for (int row = 0; row < type.rows(); row++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001412 this->writeWord(row == column ? diagonal : zeroId, out);
1413 }
1414 }
1415 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1416 out);
1417 this->writeWord(this->getType(type), out);
1418 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001419 for (SpvId columnId : columnIds) {
1420 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001421 }
1422}
1423
John Stiles268a73f2021-04-07 12:30:22 -04001424SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
1425 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001426 SkASSERT(srcType.isMatrix());
1427 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001428 SkASSERT(srcType.componentType() == dstType.componentType());
John Stiles268a73f2021-04-07 12:30:22 -04001429 SpvId id = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001430 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1431 srcType.rows(),
1432 1));
1433 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1434 dstType.rows(),
1435 1));
John Stiles92671832021-04-06 09:24:55 -04001436 SkASSERT(dstType.componentType().isFloat());
1437 FloatLiteral zero(/*offset=*/-1, /*value=*/0.0, &dstType.componentType());
1438 const SpvId zeroId = this->writeFloatLiteral(zero);
1439 FloatLiteral one(/*offset=*/-1, /*value=*/1.0, &dstType.componentType());
1440 const SpvId oneId = this->writeFloatLiteral(one);
1441
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001442 SpvId columns[4];
1443 for (int i = 0; i < dstType.columns(); i++) {
1444 if (i < srcType.columns()) {
1445 // we're still inside the src matrix, copy the column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001446 SpvId srcColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001447 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1448 SpvId dstColumn;
1449 if (srcType.rows() == dstType.rows()) {
1450 // columns are equal size, don't need to do anything
1451 dstColumn = srcColumn;
1452 }
1453 else if (dstType.rows() > srcType.rows()) {
1454 // dst column is bigger, need to zero-pad it
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001455 dstColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001456 int delta = dstType.rows() - srcType.rows();
1457 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1458 this->writeWord(dstColumnType, out);
1459 this->writeWord(dstColumn, out);
1460 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001461 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
1462 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001463 }
1464 }
1465 else {
1466 // dst column is smaller, need to swizzle the src column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001467 dstColumn = this->nextId(&dstType);
John Stiles92671832021-04-06 09:24:55 -04001468 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001469 this->writeWord(dstColumnType, out);
1470 this->writeWord(dstColumn, out);
1471 this->writeWord(srcColumn, out);
1472 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001473 for (int j = 0; j < dstType.rows(); j++) {
John Stilesf621e232020-08-25 13:33:02 -04001474 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001475 }
1476 }
1477 columns[i] = dstColumn;
1478 } else {
John Stiles92671832021-04-06 09:24:55 -04001479 // we're past the end of the src matrix, need to synthesize an identity-matrix column
1480 SpvId identityColumn = this->nextId(&dstType);
1481 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1482 this->writeWord(dstColumnType, out);
1483 this->writeWord(identityColumn, out);
1484 for (int j = 0; j < dstType.rows(); ++j) {
1485 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001486 }
John Stiles92671832021-04-06 09:24:55 -04001487 columns[i] = identityColumn;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001488 }
1489 }
1490 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1491 this->writeWord(this->getType(dstType), out);
1492 this->writeWord(id, out);
1493 for (int i = 0; i < dstType.columns(); i++) {
1494 this->writeWord(columns[i], out);
1495 }
John Stiles268a73f2021-04-07 12:30:22 -04001496 return id;
Ethan Nicholas84645e32017-02-09 13:57:14 -05001497}
1498
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001499void SPIRVCodeGenerator::addColumnEntry(SpvId columnType, Precision precision,
1500 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001501 std::vector<SpvId>* columnIds,
1502 int* currentCount, int rows, SpvId entry,
1503 OutputStream& out) {
1504 SkASSERT(*currentCount < rows);
1505 ++(*currentCount);
1506 currentColumn->push_back(entry);
1507 if (*currentCount == rows) {
1508 *currentCount = 0;
1509 this->writeOpCode(SpvOpCompositeConstruct, 3 + currentColumn->size(), out);
1510 this->writeWord(columnType, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001511 SpvId columnId = this->nextId(precision);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001512 this->writeWord(columnId, out);
1513 columnIds->push_back(columnId);
1514 for (SpvId id : *currentColumn) {
1515 this->writeWord(id, out);
1516 }
1517 currentColumn->clear();
1518 }
1519}
1520
John Stiles8cad6372021-04-07 12:31:13 -04001521SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001522 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001523 SkASSERT(type.isMatrix());
John Stiles2bec8ab2021-04-06 18:40:04 -04001524 SkASSERT(!c.arguments().empty());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001525 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001526 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1527 // an instruction
1528 std::vector<SpvId> arguments;
John Stiles2bec8ab2021-04-06 18:40:04 -04001529 arguments.reserve(c.arguments().size());
1530 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1531 arguments.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001532 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001533 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001534 int rows = type.rows();
1535 int columns = type.columns();
John Stiles268a73f2021-04-07 12:30:22 -04001536 if (arguments.size() == 1 && arg0Type.isVector()) {
1537 // Special-case handling of float4 -> mat2x2.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001538 SkASSERT(type.rows() == 2 && type.columns() == 2);
1539 SkASSERT(arg0Type.columns() == 4);
1540 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001541 SpvId v[4];
1542 for (int i = 0; i < 4; ++i) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001543 v[i] = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001544 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1545 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001546 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001547 SpvId columnType = this->getType(type.componentType().toCompound(fContext, 2, 1));
Ethan Nicholas7f015882021-03-23 14:16:52 -04001548 SpvId column1 = this->nextId(&type);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001549 this->writeInstruction(SpvOpCompositeConstruct, columnType, column1, v[0], v[1], out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04001550 SpvId column2 = this->nextId(&type);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001551 this->writeInstruction(SpvOpCompositeConstruct, columnType, column2, v[2], v[3], out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001552 this->writeInstruction(SpvOpCompositeConstruct, this->getType(type), result, column1,
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001553 column2, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001554 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001555 SpvId columnType = this->getType(type.componentType().toCompound(fContext, rows, 1));
ethannicholasb3058bd2016-07-01 08:22:01 -07001556 std::vector<SpvId> columnIds;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001557 // ids of vectors and scalars we have written to the current column so far
1558 std::vector<SpvId> currentColumn;
1559 // the total number of scalars represented by currentColumn's entries
ethannicholasb3058bd2016-07-01 08:22:01 -07001560 int currentCount = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001561 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
ethannicholasb3058bd2016-07-01 08:22:01 -07001562 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001563 const Type& argType = c.arguments()[i]->type();
John Stiles9aeed132020-11-24 17:36:06 -05001564 if (currentCount == 0 && argType.isVector() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001565 argType.columns() == type.rows()) {
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001566 // this is a complete column by itself
ethannicholasb3058bd2016-07-01 08:22:01 -07001567 columnIds.push_back(arguments[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07001568 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001569 if (argType.columns() == 1) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001570 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1571 &currentCount, rows, arguments[i], out);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001572 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001573 SpvId componentType = this->getType(argType.componentType());
1574 for (int j = 0; j < argType.columns(); ++j) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001575 SpvId swizzle = this->nextId(&argType);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001576 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1577 arguments[i], j, out);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001578 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1579 &currentCount, rows, swizzle, out);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001580 }
1581 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001582 }
1583 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001584 SkASSERT(columnIds.size() == (size_t) columns);
ethannicholasb3058bd2016-07-01 08:22:01 -07001585 this->writeOpCode(SpvOpCompositeConstruct, 3 + columns, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001586 this->writeWord(this->getType(type), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001587 this->writeWord(result, out);
1588 for (SpvId id : columnIds) {
1589 this->writeWord(id, out);
1590 }
1591 }
1592 return result;
1593}
1594
John Stiles8cad6372021-04-07 12:31:13 -04001595SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1596 OutputStream& out) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001597 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
1598 : this->writeVectorConstructor(c, out);
1599}
1600
John Stiles8cad6372021-04-07 12:31:13 -04001601SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001602 const Type& type = c.type();
John Stilesd986f472021-04-06 15:54:43 -04001603 const Type& componentType = type.componentType();
John Stiles9aeed132020-11-24 17:36:06 -05001604 SkASSERT(type.isVector());
John Stilesd986f472021-04-06 15:54:43 -04001605
1606 if (c.isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001607 return this->writeConstantVector(c);
1608 }
John Stilesd986f472021-04-06 15:54:43 -04001609
ethannicholasb3058bd2016-07-01 08:22:01 -07001610 std::vector<SpvId> arguments;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001611 for (size_t i = 0; i < c.arguments().size(); i++) {
1612 const Type& argType = c.arguments()[i]->type();
John Stilesd986f472021-04-06 15:54:43 -04001613 SkASSERT(componentType == argType.componentType());
John Stiles48c28842021-01-14 11:05:03 -05001614
John Stilesd986f472021-04-06 15:54:43 -04001615 if (argType.isVector()) {
1616 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
1617 // vector arguments at all, so we always extract each vector component and pass them
1618 // into OpCompositeConstruct individually.
1619 SpvId vec = this->writeExpression(*c.arguments()[i], out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001620 for (int j = 0; j < argType.columns(); j++) {
John Stilesd986f472021-04-06 15:54:43 -04001621 SpvId componentId = this->nextId(&componentType);
1622 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
1623 componentId, vec, j, out);
1624 arguments.push_back(componentId);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001625 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001626 } else {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001627 arguments.push_back(this->writeExpression(*c.arguments()[i], out));
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001628 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001629 }
John Stilesb14a8192021-04-05 11:40:46 -04001630
1631 return this->writeComposite(arguments, type, out);
1632}
1633
1634SpvId SPIRVCodeGenerator::writeComposite(const std::vector<SpvId>& arguments,
1635 const Type& type,
1636 OutputStream& out) {
John Stilesd47330f2021-04-08 23:25:52 -04001637 SkASSERT(arguments.size() == (type.isStruct() ? type.fields().size() : (size_t)type.columns()));
John Stiles2938eea2021-04-01 18:58:25 -04001638
Ethan Nicholas7f015882021-03-23 14:16:52 -04001639 SpvId result = this->nextId(&type);
John Stiles2938eea2021-04-01 18:58:25 -04001640 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1641 this->writeWord(this->getType(type), out);
1642 this->writeWord(result, out);
1643 for (SpvId id : arguments) {
1644 this->writeWord(id, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001645 }
1646 return result;
1647}
1648
John Stiles2938eea2021-04-01 18:58:25 -04001649SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, OutputStream& out) {
1650 // Use writeConstantVector to deduplicate constant splats.
1651 if (c.isCompileTimeConstant()) {
1652 return this->writeConstantVector(c);
1653 }
1654
1655 // Write the splat argument.
1656 SpvId argument = this->writeExpression(*c.argument(), out);
1657
1658 // Generate a OpCompositeConstruct which repeats the argument N times.
John Stilesb14a8192021-04-05 11:40:46 -04001659 std::vector<SpvId> arguments(/*count*/ c.type().columns(), /*value*/ argument);
1660 return this->writeComposite(arguments, c.type(), out);
John Stiles2938eea2021-04-01 18:58:25 -04001661}
1662
1663
John Stilesd47330f2021-04-08 23:25:52 -04001664SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, OutputStream& out) {
1665 SkASSERT(c.type().isArray() || c.type().isStruct());
1666 auto ctorArgs = c.argumentSpan();
1667
Ethan Nicholasbd553222017-07-18 15:54:59 -04001668 std::vector<SpvId> arguments;
John Stilesd47330f2021-04-08 23:25:52 -04001669 arguments.reserve(ctorArgs.size());
1670 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
1671 arguments.push_back(this->writeExpression(*arg, out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001672 }
John Stilesd47330f2021-04-08 23:25:52 -04001673
1674 return this->writeComposite(arguments, c.type(), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001675}
1676
John Stilesfd7252f2021-04-04 22:24:40 -04001677SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1678 OutputStream& out) {
1679 const Type& type = c.type();
1680 if (this->getActualType(type) == this->getActualType(c.argument()->type())) {
1681 return this->writeExpression(*c.argument(), out);
1682 }
John Stilesb14a8192021-04-05 11:40:46 -04001683
1684 const Expression& ctorExpr = *c.argument();
1685 SpvId expressionId = this->writeExpression(ctorExpr, out);
1686 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
1687}
1688
John Stiles8cad6372021-04-07 12:31:13 -04001689SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
1690 OutputStream& out) {
John Stilesb14a8192021-04-05 11:40:46 -04001691 const Type& ctorType = c.type();
1692 const Type& argType = c.argument()->type();
John Stiles268a73f2021-04-07 12:30:22 -04001693 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
John Stilesb14a8192021-04-05 11:40:46 -04001694
John Stiles268a73f2021-04-07 12:30:22 -04001695 // Write the composite that we are casting. If the actual type matches, we are done.
1696 SpvId compositeId = this->writeExpression(*c.argument(), out);
John Stilesb14a8192021-04-05 11:40:46 -04001697 if (this->getActualType(ctorType) == this->getActualType(argType)) {
John Stiles268a73f2021-04-07 12:30:22 -04001698 return compositeId;
1699 }
1700
1701 // writeMatrixCopy can cast matrices to a different type.
1702 if (ctorType.isMatrix()) {
1703 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
John Stilesfd7252f2021-04-04 22:24:40 -04001704 }
John Stilesb14a8192021-04-05 11:40:46 -04001705
1706 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
John Stilesd986f472021-04-06 15:54:43 -04001707 // components and convert each one manually.
John Stilesb14a8192021-04-05 11:40:46 -04001708 const Type& srcType = argType.componentType();
1709 const Type& dstType = ctorType.componentType();
1710
1711 std::vector<SpvId> arguments;
John Stiles268a73f2021-04-07 12:30:22 -04001712 arguments.reserve(argType.columns());
John Stilesb14a8192021-04-05 11:40:46 -04001713 for (int index = 0; index < argType.columns(); ++index) {
1714 SpvId componentId = this->nextId(&srcType);
1715 this->writeInstruction(SpvOpCompositeExtract, this->getType(srcType), componentId,
John Stiles268a73f2021-04-07 12:30:22 -04001716 compositeId, index, out);
John Stilesb14a8192021-04-05 11:40:46 -04001717 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
John Stilesfd7252f2021-04-04 22:24:40 -04001718 }
John Stilesb14a8192021-04-05 11:40:46 -04001719
1720 return this->writeComposite(arguments, ctorType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001721}
1722
John Stilese1182782021-03-30 22:09:37 -04001723SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
1724 OutputStream& out) {
1725 const Type& type = c.type();
1726 SkASSERT(type.isMatrix());
1727 SkASSERT(c.argument()->type().isScalar());
1728
1729 // Write out the scalar argument.
1730 SpvId argument = this->writeExpression(*c.argument(), out);
1731
1732 // Build the diagonal matrix.
1733 SpvId result = this->nextId(&type);
1734 this->writeUniformScaleMatrix(result, argument, type, out);
1735 return result;
1736}
1737
John Stiles5abb9e12021-04-06 13:47:19 -04001738SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1739 OutputStream& out) {
1740 // Write the input matrix.
1741 SpvId argument = this->writeExpression(*c.argument(), out);
1742
1743 // Use matrix-copy to resize the input matrix to its new size.
John Stiles268a73f2021-04-07 12:30:22 -04001744 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
John Stiles5abb9e12021-04-06 13:47:19 -04001745}
1746
John Stiles9485b552021-01-27 11:47:00 -05001747static SpvStorageClass_ get_storage_class(const Variable& var,
1748 SpvStorageClass_ fallbackStorageClass) {
1749 const Modifiers& modifiers = var.modifiers();
ethannicholasb3058bd2016-07-01 08:22:01 -07001750 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001751 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001752 return SpvStorageClassInput;
John Stiles9485b552021-01-27 11:47:00 -05001753 }
1754 if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001755 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001756 return SpvStorageClassOutput;
John Stiles9485b552021-01-27 11:47:00 -05001757 }
1758 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001759 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001760 return SpvStorageClassPushConstant;
1761 }
John Stiles9485b552021-01-27 11:47:00 -05001762 if (var.type().typeKind() == Type::TypeKind::kSampler ||
1763 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
1764 var.type().typeKind() == Type::TypeKind::kTexture) {
1765 return SpvStorageClassUniformConstant;
1766 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001767 return SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07001768 }
John Stiles9485b552021-01-27 11:47:00 -05001769 return fallbackStorageClass;
ethannicholasb3058bd2016-07-01 08:22:01 -07001770}
1771
John Stiles9485b552021-01-27 11:47:00 -05001772static SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001773 switch (expr.kind()) {
1774 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001775 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001776 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001777 return SpvStorageClassFunction;
1778 }
John Stiles9485b552021-01-27 11:47:00 -05001779 return get_storage_class(var, SpvStorageClassPrivate);
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001780 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001781 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001782 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001783 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001784 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001785 default:
1786 return SpvStorageClassFunction;
1787 }
1788}
1789
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001790std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001791 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001792 switch (expr.kind()) {
1793 case Expression::Kind::kIndex: {
John Stiles0693fb82021-01-22 18:27:52 -05001794 const IndexExpression& indexExpr = expr.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001795 chain = this->getAccessChain(*indexExpr.base(), out);
1796 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001797 break;
1798 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001799 case Expression::Kind::kFieldAccess: {
John Stiles0693fb82021-01-22 18:27:52 -05001800 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001801 chain = this->getAccessChain(*fieldExpr.base(), out);
John Stiles9ce80f72021-03-11 22:35:19 -05001802 IntLiteral index(/*offset=*/-1, fieldExpr.fieldIndex(), fContext.fTypes.fInt.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07001803 chain.push_back(this->writeIntLiteral(index));
1804 break;
1805 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001806 default: {
1807 SpvId id = this->getLValue(expr, out)->getPointer();
John Stiles3f14d282021-02-05 09:31:04 -05001808 SkASSERT(id != (SpvId) -1);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001809 chain.push_back(id);
1810 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001811 }
1812 return chain;
1813}
1814
1815class PointerLValue : public SPIRVCodeGenerator::LValue {
1816public:
Ethan Nicholase0707b72021-03-17 11:16:41 -04001817 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001818 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001819 : fGen(gen)
1820 , fPointer(pointer)
Ethan Nicholase0707b72021-03-17 11:16:41 -04001821 , fIsMemoryObject(isMemoryObject)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001822 , fType(type)
1823 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001824
John Stiles1cf2c8d2020-08-13 22:58:04 -04001825 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001826 return fPointer;
1827 }
1828
Ethan Nicholase0707b72021-03-17 11:16:41 -04001829 bool isMemoryObjectPointer() const override {
1830 return fIsMemoryObject;
1831 }
1832
John Stiles1cf2c8d2020-08-13 22:58:04 -04001833 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001834 SpvId result = fGen.nextId(fPrecision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001835 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1836 return result;
1837 }
1838
John Stiles1cf2c8d2020-08-13 22:58:04 -04001839 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001840 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1841 }
1842
1843private:
1844 SPIRVCodeGenerator& fGen;
1845 const SpvId fPointer;
Ethan Nicholase0707b72021-03-17 11:16:41 -04001846 const bool fIsMemoryObject;
ethannicholasb3058bd2016-07-01 08:22:01 -07001847 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001848 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001849};
1850
1851class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1852public:
John Stiles750109b2020-10-30 13:45:46 -04001853 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001854 const Type& baseType, const Type& swizzleType)
ethannicholasb3058bd2016-07-01 08:22:01 -07001855 : fGen(gen)
1856 , fVecPointer(vecPointer)
1857 , fComponents(components)
John Stiles3f14d282021-02-05 09:31:04 -05001858 , fBaseType(&baseType)
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001859 , fSwizzleType(&swizzleType) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001860
John Stiles3f14d282021-02-05 09:31:04 -05001861 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
1862 ComponentArray updatedSwizzle;
1863 for (int8_t component : components) {
1864 if (component < 0 || component >= fComponents.count()) {
1865 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
1866 return false;
1867 }
1868 updatedSwizzle.push_back(fComponents[component]);
1869 }
1870 fComponents = updatedSwizzle;
1871 fSwizzleType = &newType;
1872 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001873 }
1874
John Stiles1cf2c8d2020-08-13 22:58:04 -04001875 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001876 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001877 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001878 SpvId result = fGen.nextId(fBaseType);
ethannicholasb3058bd2016-07-01 08:22:01 -07001879 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
John Stiles3f14d282021-02-05 09:31:04 -05001880 fGen.writeWord(fGen.getType(*fSwizzleType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001881 fGen.writeWord(result, out);
1882 fGen.writeWord(base, out);
1883 fGen.writeWord(base, out);
1884 for (int component : fComponents) {
1885 fGen.writeWord(component, out);
1886 }
1887 return result;
1888 }
1889
John Stiles1cf2c8d2020-08-13 22:58:04 -04001890 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001891 // use OpVectorShuffle to mix and match the vector components. We effectively create
1892 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001893 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001894 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001895 // float3L = ...;
1896 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001897 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001898 // we end up with the virtual vector (L.x, L.y, L.z, R.x, R.y, R.z). Then we want
ethannicholasb3058bd2016-07-01 08:22:01 -07001899 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1900 // (3, 1, 4).
Ethan Nicholas7f015882021-03-23 14:16:52 -04001901 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001902 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001903 SpvId shuffle = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001904 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
1905 fGen.writeWord(fGen.getType(*fBaseType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001906 fGen.writeWord(shuffle, out);
1907 fGen.writeWord(base, out);
1908 fGen.writeWord(value, out);
John Stiles3f14d282021-02-05 09:31:04 -05001909 for (int i = 0; i < fBaseType->columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001910 // current offset into the virtual vector, defaults to pulling the unmodified
1911 // value from the left side
1912 int offset = i;
1913 // check to see if we are writing this component
1914 for (size_t j = 0; j < fComponents.size(); j++) {
1915 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001916 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001917 // the correct component of the right side instead of preserving the
1918 // value from the left
John Stiles3f14d282021-02-05 09:31:04 -05001919 offset = (int) (j + fBaseType->columns());
ethannicholasb3058bd2016-07-01 08:22:01 -07001920 break;
1921 }
1922 }
1923 fGen.writeWord(offset, out);
1924 }
1925 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1926 }
1927
1928private:
1929 SPIRVCodeGenerator& fGen;
1930 const SpvId fVecPointer;
John Stiles3f14d282021-02-05 09:31:04 -05001931 ComponentArray fComponents;
1932 const Type* fBaseType;
1933 const Type* fSwizzleType;
ethannicholasb3058bd2016-07-01 08:22:01 -07001934};
1935
John Stilese40d1662021-01-29 10:08:50 -05001936int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
1937 auto iter = fTopLevelUniformMap.find(&var);
1938 return (iter != fTopLevelUniformMap.end()) ? iter->second : -1;
1939}
1940
Greg Daniel64773e62016-11-22 09:44:03 -05001941std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001942 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001943 const Type& type = expr.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001944 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
Ethan Nicholase6592142020-09-08 10:22:09 -04001945 switch (expr.kind()) {
1946 case Expression::Kind::kVariableReference: {
John Stiles0de76f72021-01-29 09:19:39 -05001947 const Variable& var = *expr.as<VariableReference>().variable();
John Stilese40d1662021-01-29 10:08:50 -05001948 int uniformIdx = this->findUniformFieldIndex(var);
1949 if (uniformIdx >= 0) {
John Stiles9ce80f72021-03-11 22:35:19 -05001950 IntLiteral uniformIdxLiteral{/*offset=*/-1, uniformIdx, fContext.fTypes.fInt.get()};
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001951 SpvId memberId = this->nextId(nullptr);
John Stilese40d1662021-01-29 10:08:50 -05001952 SpvId typeId = this->getPointerType(type, SpvStorageClassUniform);
1953 SpvId uniformIdxId = this->writeIntLiteral(uniformIdxLiteral);
1954 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
1955 uniformIdxId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04001956 return std::make_unique<PointerLValue>(*this, memberId,
1957 /*isMemoryObjectPointer=*/true,
1958 this->getType(type), precision);
John Stilese40d1662021-01-29 10:08:50 -05001959 }
1960 SpvId typeId;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001961 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
John Stilesad2d4942020-12-11 16:55:58 -05001962 typeId = this->getType(*Type::MakeArrayType("sk_in", var.type().componentType(),
1963 fSkInCount));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001964 } else {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05001965 typeId = this->getType(type, this->memoryLayoutForVariable(var));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001966 }
ethannicholasd598f792016-07-25 10:08:54 -07001967 auto entry = fVariableMap.find(&var);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001968 SkASSERT(entry != fVariableMap.end());
Ethan Nicholase0707b72021-03-17 11:16:41 -04001969 return std::make_unique<PointerLValue>(*this, entry->second,
1970 /*isMemoryObjectPointer=*/true,
1971 typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001972 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001973 case Expression::Kind::kIndex: // fall through
1974 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001975 std::vector<SpvId> chain = this->getAccessChain(expr, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001976 SpvId member = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001977 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001978 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001979 this->writeWord(member, out);
1980 for (SpvId idx : chain) {
1981 this->writeWord(idx, out);
1982 }
Ethan Nicholase0707b72021-03-17 11:16:41 -04001983 return std::make_unique<PointerLValue>(*this, member, /*isMemoryObjectPointer=*/false,
1984 this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001985 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001986 case Expression::Kind::kSwizzle: {
John Stiles0693fb82021-01-22 18:27:52 -05001987 const Swizzle& swizzle = expr.as<Swizzle>();
John Stiles3f14d282021-02-05 09:31:04 -05001988 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
1989 if (lvalue->applySwizzle(swizzle.components(), type)) {
1990 return lvalue;
1991 }
1992 SpvId base = lvalue->getPointer();
1993 if (base == (SpvId) -1) {
John Stiles5570c512020-11-19 17:58:07 -05001994 fErrors.error(swizzle.fOffset, "unable to retrieve lvalue from swizzle");
1995 }
John Stiles3f14d282021-02-05 09:31:04 -05001996 if (swizzle.components().size() == 1) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001997 SpvId member = this->nextId(nullptr);
John Stilesb5db4822021-01-21 13:04:40 -05001998 SpvId typeId = this->getPointerType(type, get_storage_class(*swizzle.base()));
John Stiles9ce80f72021-03-11 22:35:19 -05001999 IntLiteral index(/*offset=*/-1, swizzle.components()[0],
2000 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -05002001 SpvId indexId = this->writeIntLiteral(index);
2002 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002003 return std::make_unique<PointerLValue>(*this,
2004 member,
2005 /*isMemoryObjectPointer=*/false,
2006 this->getType(type),
John Stiles5570c512020-11-19 17:58:07 -05002007 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002008 } else {
John Stiles5570c512020-11-19 17:58:07 -05002009 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002010 swizzle.base()->type(), type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002011 }
2012 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002013 default: {
ethannicholasb3058bd2016-07-01 08:22:01 -07002014 // expr isn't actually an lvalue, create a dummy variable for it. This case happens due
Greg Daniel64773e62016-11-22 09:44:03 -05002015 // to the need to store values in temporary variables during function calls (see
ethannicholasb3058bd2016-07-01 08:22:01 -07002016 // comments in getFunctionType); erroneous uses of rvalues as lvalues should have been
2017 // caught by IRGenerator
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002018 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002019 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
2020 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07002021 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002022 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002023 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
2024 this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002025 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002026 }
2027}
2028
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002029SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
John Stiles1e1fe122021-01-29 12:18:46 -05002030 SpvId result = this->getLValue(ref, out)->load(out);
John Stilese40d1662021-01-29 10:08:50 -05002031
John Stiles1e1fe122021-01-29 12:18:46 -05002032 // Handle the "flipY" setting when reading sk_FragCoord.
2033 const Variable* variable = ref.variable();
John Stilese40d1662021-01-29 10:08:50 -05002034 if (variable->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN &&
John Stiles270cec22021-02-17 12:59:36 -05002035 fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002036 // The x component never changes, so just grab it
Ethan Nicholas7f015882021-03-23 14:16:52 -04002037 SpvId xId = this->nextId(Precision::kDefault);
John Stiles54e7c052021-01-11 14:22:36 -05002038 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat), xId,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002039 result, 0, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002040
2041 // Calculate the y component which may need to be flipped
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002042 SpvId rawYId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002043 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat),
2044 rawYId, result, 1, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002045 SpvId flippedYId = 0;
John Stiles270cec22021-02-17 12:59:36 -05002046 if (fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002047 // need to remap to a top-left coordinate system
2048 if (fRTHeightStructId == (SpvId)-1) {
2049 // height variable hasn't been written yet
Greg Daniela85e4bf2020-06-17 16:32:45 -04002050 SkASSERT(fRTHeightFieldIndex == (SpvId)-1);
2051 std::vector<Type::Field> fields;
John Stiles270cec22021-02-17 12:59:36 -05002052 if (fProgram.fConfig->fSettings.fRTHeightOffset < 0) {
John Stiles5570c512020-11-19 17:58:07 -05002053 fErrors.error(ref.fOffset, "RTHeightOffset is negative");
2054 }
Greg Daniela85e4bf2020-06-17 16:32:45 -04002055 fields.emplace_back(
John Stilese40d1662021-01-29 10:08:50 -05002056 Modifiers(Layout(/*flags=*/0, /*location=*/-1,
John Stiles270cec22021-02-17 12:59:36 -05002057 fProgram.fConfig->fSettings.fRTHeightOffset,
John Stilese40d1662021-01-29 10:08:50 -05002058 /*binding=*/-1, /*index=*/-1, /*set=*/-1, /*builtin=*/-1,
Brian Osman4717fbb2021-02-23 13:12:09 -05002059 /*inputAttachmentIndex=*/-1,
John Stilese40d1662021-01-29 10:08:50 -05002060 Layout::kUnspecified_Primitive, /*maxVertices=*/1,
Brian Osman8f1dff62021-04-19 13:50:58 -04002061 /*invocations=*/-1, /*when=*/"", Layout::CType::kDefault),
John Stilese40d1662021-01-29 10:08:50 -05002062 /*flags=*/0),
John Stiles54e7c052021-01-11 14:22:36 -05002063 SKSL_RTHEIGHT_NAME, fContext.fTypes.fFloat.get());
Greg Daniela85e4bf2020-06-17 16:32:45 -04002064 StringFragment name("sksl_synthetic_uniforms");
John Stilesad2d4942020-12-11 16:55:58 -05002065 std::unique_ptr<Type> intfStruct = Type::MakeStructType(/*offset=*/-1, name,
2066 fields);
John Stiles270cec22021-02-17 12:59:36 -05002067 int binding = fProgram.fConfig->fSettings.fRTHeightBinding;
John Stiles5570c512020-11-19 17:58:07 -05002068 if (binding == -1) {
2069 fErrors.error(ref.fOffset, "layout(binding=...) is required in SPIR-V");
2070 }
John Stiles270cec22021-02-17 12:59:36 -05002071 int set = fProgram.fConfig->fSettings.fRTHeightSet;
John Stiles5570c512020-11-19 17:58:07 -05002072 if (set == -1) {
2073 fErrors.error(ref.fOffset, "layout(set=...) is required in SPIR-V");
2074 }
John Stiles270cec22021-02-17 12:59:36 -05002075 bool usePushConstants = fProgram.fConfig->fSettings.fUsePushConstants;
John Stilese40d1662021-01-29 10:08:50 -05002076 int flags = usePushConstants ? Layout::Flag::kPushConstant_Flag : 0;
2077 Modifiers modifiers(
2078 Layout(flags, /*location=*/-1, /*offset=*/-1, binding, /*index=*/-1,
2079 set, /*builtin=*/-1, /*inputAttachmentIndex=*/-1,
Brian Osman4717fbb2021-02-23 13:12:09 -05002080 Layout::kUnspecified_Primitive,
Brian Osman8f1dff62021-04-19 13:50:58 -04002081 /*maxVertices=*/-1, /*invocations=*/-1, /*when=*/"",
Brian Osmanba7ef322021-02-23 13:37:22 -05002082 Layout::CType::kDefault),
John Stilese40d1662021-01-29 10:08:50 -05002083 Modifiers::kUniform_Flag);
John Stiles3ae071e2020-08-05 15:29:29 -04002084 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
2085 std::make_unique<Variable>(/*offset=*/-1,
John Stilesf2872e62021-05-04 11:38:43 -04002086 fProgram.fModifiers->add(modifiers),
John Stiles3ae071e2020-08-05 15:29:29 -04002087 name,
John Stilesad2d4942020-12-11 16:55:58 -05002088 intfStruct.get(),
Brian Osman3887a012020-09-30 13:22:27 -04002089 /*builtin=*/false,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002090 Variable::Storage::kGlobal));
John Stilesd39aec02020-12-03 10:42:26 -05002091 InterfaceBlock intf(/*offset=*/-1, intfVar, name,
2092 /*instanceName=*/"", /*arraySize=*/0,
John Stiles7c3515b2020-10-16 18:38:39 -04002093 std::make_shared<SymbolTable>(&fErrors, /*builtin=*/false));
Stephen White88574972020-06-23 19:09:29 -04002094
2095 fRTHeightStructId = this->writeInterfaceBlock(intf, false);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002096 fRTHeightFieldIndex = 0;
Jim Van Verth46e9b0e2021-01-28 17:26:48 -05002097 fRTHeightStorageClass = usePushConstants ? SpvStorageClassPushConstant
2098 : SpvStorageClassUniform;
Greg Daniela85e4bf2020-06-17 16:32:45 -04002099 }
2100 SkASSERT(fRTHeightFieldIndex != (SpvId)-1);
2101
John Stiles9ce80f72021-03-11 22:35:19 -05002102 IntLiteral fieldIndex(/*offset=*/-1, fRTHeightFieldIndex, fContext.fTypes.fInt.get());
Greg Daniela85e4bf2020-06-17 16:32:45 -04002103 SpvId fieldIndexId = this->writeIntLiteral(fieldIndex);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002104 SpvId heightPtr = this->nextId(nullptr);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002105 this->writeOpCode(SpvOpAccessChain, 5, out);
John Stiles54e7c052021-01-11 14:22:36 -05002106 this->writeWord(this->getPointerType(*fContext.fTypes.fFloat, fRTHeightStorageClass),
Greg Daniela85e4bf2020-06-17 16:32:45 -04002107 out);
2108 this->writeWord(heightPtr, out);
2109 this->writeWord(fRTHeightStructId, out);
2110 this->writeWord(fieldIndexId, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002111 SpvId heightRead = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002112 this->writeInstruction(SpvOpLoad, this->getType(*fContext.fTypes.fFloat), heightRead,
Greg Daniela85e4bf2020-06-17 16:32:45 -04002113 heightPtr, out);
2114
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002115 flippedYId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002116 this->writeInstruction(SpvOpFSub, this->getType(*fContext.fTypes.fFloat), flippedYId,
Greg Daniela85e4bf2020-06-17 16:32:45 -04002117 heightRead, rawYId, out);
2118 }
2119
2120 // The z component will always be zero so we just get an id to the 0 literal
John Stiles9ce80f72021-03-11 22:35:19 -05002121 FloatLiteral zero(/*offset=*/-1, /*value=*/0.0, fContext.fTypes.fFloat.get());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002122 SpvId zeroId = writeFloatLiteral(zero);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002123
Brian Osmane38bedd2020-12-21 11:51:54 -05002124 // Calculate the w component
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002125 SpvId rawWId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002126 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat),
2127 rawWId, result, 3, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002128
2129 // Fill in the new fragcoord with the components from above
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002130 SpvId adjusted = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002131 this->writeOpCode(SpvOpCompositeConstruct, 7, out);
John Stiles54e7c052021-01-11 14:22:36 -05002132 this->writeWord(this->getType(*fContext.fTypes.fFloat4), out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002133 this->writeWord(adjusted, out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002134 this->writeWord(xId, out);
John Stiles270cec22021-02-17 12:59:36 -05002135 if (fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002136 this->writeWord(flippedYId, out);
2137 } else {
2138 this->writeWord(rawYId, out);
2139 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002140 this->writeWord(zeroId, out);
Brian Osmane38bedd2020-12-21 11:51:54 -05002141 this->writeWord(rawWId, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002142
2143 return adjusted;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002144 }
John Stiles1e1fe122021-01-29 12:18:46 -05002145
2146 // Handle the "flipY" setting when reading sk_Clockwise.
John Stilese40d1662021-01-29 10:08:50 -05002147 if (variable->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN &&
John Stiles270cec22021-02-17 12:59:36 -05002148 !fProgram.fConfig->fSettings.fFlipY) {
Chris Daltonb91c4662018-08-01 10:46:22 -06002149 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia, we use
2150 // the default convention of "counter-clockwise face is front".
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002151 SpvId inverse = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002152 this->writeInstruction(SpvOpLogicalNot, this->getType(*fContext.fTypes.fBool), inverse,
Chris Daltonb91c4662018-08-01 10:46:22 -06002153 result, out);
2154 return inverse;
2155 }
John Stiles1e1fe122021-01-29 12:18:46 -05002156
ethannicholasb3058bd2016-07-01 08:22:01 -07002157 return result;
2158}
2159
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002160SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002161 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002162 SpvId base = this->writeExpression(*expr.base(), out);
2163 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002164 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002165 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002166 index, out);
2167 return result;
2168 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002169 return getLValue(expr, out)->load(out);
2170}
2171
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002172SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002173 return getLValue(f, out)->load(out);
2174}
2175
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002176SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002177 SpvId base = this->writeExpression(*swizzle.base(), out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002178 SpvId result = this->nextId(&swizzle.type());
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002179 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002180 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002181 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002182 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002183 } else {
2184 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002185 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002186 this->writeWord(result, out);
2187 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002188 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002189 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002190 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002191 }
2192 }
2193 return result;
2194}
2195
Greg Daniel64773e62016-11-22 09:44:03 -05002196SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2197 const Type& operandType, SpvId lhs,
2198 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002199 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002200 SpvId result = this->nextId(&resultType);
ethannicholasd598f792016-07-25 10:08:54 -07002201 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002202 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002203 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002204 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002205 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002206 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002207 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002208 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2209 } else {
John Stiles123501f2020-12-09 10:08:13 -05002210 fErrors.error(operandType.fOffset,
2211 "unsupported operand for binary expression: " + operandType.description());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002212 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002213 return result;
2214}
2215
Ethan Nicholas48e24052018-03-14 13:51:39 -04002216SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2217 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002218 if (operandType.isVector()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002219 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002220 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002221 return result;
2222 }
2223 return id;
2224}
2225
Ethan Nicholas68990be2017-07-13 09:36:52 -04002226SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2227 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002228 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002229 OutputStream& out) {
2230 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002231 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002232 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2233 operandType.rows(),
2234 1));
John Stiles54e7c052021-01-11 14:22:36 -05002235 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002236 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002237 1));
John Stiles54e7c052021-01-11 14:22:36 -05002238 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002239 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002240 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002241 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002242 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002243 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002244 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002245 SpvId compare = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002246 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002247 SpvId merge = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002248 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002249 if (result != 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002250 SpvId next = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002251 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002252 result = next;
2253 }
2254 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002255 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002256 }
2257 }
2258 return result;
2259}
2260
Ethan Nicholas0df21132018-07-10 09:37:51 -04002261SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
John Stiles43b593c2021-05-13 22:03:27 -04002262 SpvId rhs, SpvOp_ op, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002263 SkASSERT(operandType.isMatrix());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002264 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2265 operandType.rows(),
2266 1));
John Stiles43b593c2021-05-13 22:03:27 -04002267 std::vector<SpvId> columns;
2268 columns.reserve(operandType.columns());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002269 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002270 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002271 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002272 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002273 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
John Stiles43b593c2021-05-13 22:03:27 -04002274 columns.push_back(this->nextId(&operandType));
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002275 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002276 }
John Stiles43b593c2021-05-13 22:03:27 -04002277 return this->writeComposite(columns, operandType, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002278}
2279
John Stiles9485b552021-01-27 11:47:00 -05002280static std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002281 if (type.isInteger()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002282 return IntLiteral::Make(/*offset=*/-1, /*value=*/1, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002283 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002284 else if (type.isFloat()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002285 return FloatLiteral::Make(/*offset=*/-1, /*value=*/1.0, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002286 } else {
John Stilesf57207b2021-02-02 17:50:34 -05002287 SK_ABORT("math is unsupported on type '%s'", String(type.name()).c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -07002288 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002289}
2290
John Stilesd94bfdd2021-03-25 11:44:08 -04002291SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, OutputStream& out) {
2292 SkASSERT(type.isFloat());
2293 SpvId one = this->writeFloatLiteral({/*offset=*/-1, /*value=*/1, &type});
2294 SpvId reciprocal = this->nextId(&type);
2295 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
2296 return reciprocal;
2297}
2298
John Stiles45990502021-02-16 10:55:27 -05002299SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
Ethan Nicholas49465b42019-04-17 12:22:21 -04002300 const Type& rightType, SpvId rhs,
2301 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002302 // The comma operator ignores the type of the left-hand side entirely.
John Stiles45990502021-02-16 10:55:27 -05002303 if (op.kind() == Token::Kind::TK_COMMA) {
John Stilesd0614f22020-12-09 11:11:41 -05002304 return rhs;
2305 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002306 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002307 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002308 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2309 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002310 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002311 if (leftType.isVector() && rightType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002312 if (resultType.componentType().isFloat()) {
2313 switch (op.kind()) {
2314 case Token::Kind::TK_SLASH: {
2315 rhs = this->writeReciprocal(rightType, rhs, out);
2316 [[fallthrough]];
2317 }
2318 case Token::Kind::TK_STAR: {
2319 SpvId result = this->nextId(&resultType);
2320 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2321 result, lhs, rhs, out);
2322 return result;
2323 }
2324 default:
2325 break;
2326 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002327 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002328 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002329 const Type& vecType = leftType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002330 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002331 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2332 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002333 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002334 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002335 this->writeWord(rhs, out);
2336 }
2337 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002338 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002339 } else if (rightType.isVector() && leftType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002340 if (resultType.componentType().isFloat()) {
2341 if (op.kind() == Token::Kind::TK_STAR) {
2342 SpvId result = this->nextId(&resultType);
2343 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2344 result, rhs, lhs, out);
2345 return result;
2346 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002347 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002348 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002349 const Type& vecType = rightType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002350 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002351 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2352 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002353 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002354 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002355 this->writeWord(lhs, out);
2356 }
2357 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002358 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002359 } else if (leftType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002360 SpvOp_ spvop;
John Stiles9aeed132020-11-24 17:36:06 -05002361 if (rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002362 spvop = SpvOpMatrixTimesMatrix;
John Stiles9aeed132020-11-24 17:36:06 -05002363 } else if (rightType.isVector()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002364 spvop = SpvOpMatrixTimesVector;
ethannicholasb3058bd2016-07-01 08:22:01 -07002365 } else {
John Stiles9aeed132020-11-24 17:36:06 -05002366 SkASSERT(rightType.isScalar());
Ethan Nicholas49465b42019-04-17 12:22:21 -04002367 spvop = SpvOpMatrixTimesScalar;
ethannicholasb3058bd2016-07-01 08:22:01 -07002368 }
Ethan Nicholas7f015882021-03-23 14:16:52 -04002369 SpvId result = this->nextId(&resultType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002370 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002371 return result;
John Stiles9aeed132020-11-24 17:36:06 -05002372 } else if (rightType.isMatrix()) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002373 SpvId result = this->nextId(&resultType);
John Stiles9aeed132020-11-24 17:36:06 -05002374 if (leftType.isVector()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002375 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType), result,
ethannicholasb3058bd2016-07-01 08:22:01 -07002376 lhs, rhs, out);
2377 } else {
John Stiles9aeed132020-11-24 17:36:06 -05002378 SkASSERT(leftType.isScalar());
Ethan Nicholas49465b42019-04-17 12:22:21 -04002379 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType), result,
2380 rhs, lhs, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002381 }
2382 return result;
2383 } else {
John Stilesd8ca6b62020-11-23 14:28:36 -05002384 fErrors.error(leftType.fOffset, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002385 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002386 }
2387 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002388 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002389 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002390 }
John Stiles45990502021-02-16 10:55:27 -05002391 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002392 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002393 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002394 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002395 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002396 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002397 if (operandType->isStruct()) {
2398 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2399 }
John Stiles35092102021-04-08 23:30:51 -04002400 if (operandType->isArray()) {
2401 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2402 }
John Stiles4a7dc462020-11-25 11:08:08 -05002403 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002404 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002405 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002406 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2407 operandType->columns(),
2408 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002409 } else {
2410 tmpType = &resultType;
2411 }
2412 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002413 SpvOpFOrdEqual, SpvOpIEqual,
2414 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002415 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002416 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002417 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002418 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002419 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002420 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002421 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002422 if (operandType->isStruct()) {
2423 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2424 }
John Stiles35092102021-04-08 23:30:51 -04002425 if (operandType->isArray()) {
2426 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2427 }
John Stiles4a7dc462020-11-25 11:08:08 -05002428 [[fallthrough]];
2429 case Token::Kind::TK_LOGICALXOR:
2430 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002431 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002432 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002433 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2434 operandType->columns(),
2435 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002436 } else {
2437 tmpType = &resultType;
2438 }
2439 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002440 SpvOpFOrdNotEqual, SpvOpINotEqual,
2441 SpvOpINotEqual, SpvOpLogicalNotEqual,
2442 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002443 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002444 case Token::Kind::TK_GT:
John Stiles4a7dc462020-11-25 11:08:08 -05002445 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002446 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2447 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002448 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002449 case Token::Kind::TK_LT:
John Stiles4a7dc462020-11-25 11:08:08 -05002450 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002451 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002452 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002453 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002454 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002455 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2456 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002457 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002458 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002459 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002460 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2461 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002462 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002463 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002464 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002465 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002466 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFAdd, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002467 }
Greg Daniel64773e62016-11-22 09:44:03 -05002468 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002469 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002470 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002471 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002472 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002473 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFSub, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002474 }
Greg Daniel64773e62016-11-22 09:44:03 -05002475 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002476 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002477 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002478 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002479 // matrix multiply
Ethan Nicholas7f015882021-03-23 14:16:52 -04002480 SpvId result = this->nextId(&resultType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002481 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2482 lhs, rhs, out);
2483 return result;
2484 }
Greg Daniel64773e62016-11-22 09:44:03 -05002485 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002486 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002487 case Token::Kind::TK_SLASH:
Greg Daniel64773e62016-11-22 09:44:03 -05002488 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002489 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002490 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002491 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2492 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002493 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002494 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2495 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2496 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002497 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002498 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2499 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2500 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002501 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002502 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2503 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002504 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002505 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2506 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002507 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002508 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2509 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002510 default:
John Stiles5570c512020-11-19 17:58:07 -05002511 fErrors.error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002512 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002513 }
2514}
2515
John Stiles35092102021-04-08 23:30:51 -04002516SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
2517 SpvId rhs, OutputStream& out) {
2518 // The inputs must be arrays, and the op must be == or !=.
2519 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
2520 SkASSERT(arrayType.isArray());
2521 const Type& componentType = arrayType.componentType();
2522 const SpvId componentTypeId = this->getType(componentType);
2523 const int arraySize = arrayType.columns();
2524 SkASSERT(arraySize > 0);
2525
2526 // Synthesize equality checks for each item in the array.
2527 const Type& boolType = *fContext.fTypes.fBool;
2528 SpvId allComparisons = (SpvId)-1;
2529 for (int index = 0; index < arraySize; ++index) {
2530 // Get the left and right item in the array.
2531 SpvId itemL = this->nextId(&componentType);
2532 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemL, lhs, index, out);
2533 SpvId itemR = this->nextId(&componentType);
2534 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemR, rhs, index, out);
2535 // Use `writeBinaryExpression` with the requested == or != operator on these items.
2536 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
2537 componentType, itemR, boolType, out);
2538 // Merge this comparison result with all the other comparisons we've done.
2539 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
2540 }
2541 return allComparisons;
2542}
2543
John Stilesbc5c2a02021-04-08 11:44:53 -04002544SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
2545 SpvId rhs, OutputStream& out) {
2546 // The inputs must be structs containing fields, and the op must be == or !=.
John Stilesbc5c2a02021-04-08 11:44:53 -04002547 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
John Stiles35092102021-04-08 23:30:51 -04002548 SkASSERT(structType.isStruct());
John Stilesbc5c2a02021-04-08 11:44:53 -04002549 const std::vector<Type::Field>& fields = structType.fields();
2550 SkASSERT(!fields.empty());
2551
2552 // Synthesize equality checks for each field in the struct.
2553 const Type& boolType = *fContext.fTypes.fBool;
John Stilesbc5c2a02021-04-08 11:44:53 -04002554 SpvId allComparisons = (SpvId)-1;
2555 for (int index = 0; index < (int)fields.size(); ++index) {
2556 // Get the left and right versions of this field.
2557 const Type& fieldType = *fields[index].fType;
John Stiles35092102021-04-08 23:30:51 -04002558 const SpvId fieldTypeId = this->getType(fieldType);
John Stilesbc5c2a02021-04-08 11:44:53 -04002559
2560 SpvId fieldL = this->nextId(&fieldType);
2561 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldL, lhs, index, out);
2562 SpvId fieldR = this->nextId(&fieldType);
2563 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldR, rhs, index, out);
2564 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
2565 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
2566 boolType, out);
John Stiles35092102021-04-08 23:30:51 -04002567 // Merge this comparison result with all the other comparisons we've done.
2568 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002569 }
2570 return allComparisons;
2571}
2572
John Stiles35092102021-04-08 23:30:51 -04002573SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
2574 OutputStream& out) {
2575 // If this is the first entry, we don't need to merge comparison results with anything.
2576 if (allComparisons == (SpvId)-1) {
2577 return comparison;
2578 }
2579 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
2580 const Type& boolType = *fContext.fTypes.fBool;
2581 SpvId boolTypeId = this->getType(boolType);
2582 SpvId logicalOp = this->nextId(&boolType);
2583 switch (op.kind()) {
2584 case Token::Kind::TK_EQEQ:
2585 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
2586 comparison, allComparisons, out);
2587 break;
2588 case Token::Kind::TK_NEQ:
2589 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
2590 comparison, allComparisons, out);
2591 break;
2592 default:
2593 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
2594 return (SpvId)-1;
2595 }
2596 return logicalOp;
2597}
2598
John Stilesbc5c2a02021-04-08 11:44:53 -04002599static float division_by_literal_value(Operator op, const Expression& right) {
2600 // If this is a division by a literal value, returns that literal value. Otherwise, returns 0.
2601 if (op.kind() == Token::Kind::TK_SLASH && right.is<FloatLiteral>()) {
2602 float rhsValue = right.as<FloatLiteral>().value();
2603 if (std::isfinite(rhsValue)) {
2604 return rhsValue;
2605 }
2606 }
2607 return 0.0f;
2608}
2609
Ethan Nicholas49465b42019-04-17 12:22:21 -04002610SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2396fb82021-03-25 11:44:55 -04002611 const Expression* left = b.left().get();
2612 const Expression* right = b.right().get();
John Stiles45990502021-02-16 10:55:27 -05002613 Operator op = b.getOperator();
John Stilesbc5c2a02021-04-08 11:44:53 -04002614
John Stiles45990502021-02-16 10:55:27 -05002615 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002616 case Token::Kind::TK_EQ: {
John Stilesbc5c2a02021-04-08 11:44:53 -04002617 // Handles assignment.
John Stiles2396fb82021-03-25 11:44:55 -04002618 SpvId rhs = this->writeExpression(*right, out);
2619 this->getLValue(*left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002620 return rhs;
2621 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002622 case Token::Kind::TK_LOGICALAND:
John Stilesbc5c2a02021-04-08 11:44:53 -04002623 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2624 return this->writeLogicalAnd(*b.left(), *b.right(), out);
2625
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002626 case Token::Kind::TK_LOGICALOR:
John Stilesbc5c2a02021-04-08 11:44:53 -04002627 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2628 return this->writeLogicalOr(*b.left(), *b.right(), out);
2629
Ethan Nicholas49465b42019-04-17 12:22:21 -04002630 default:
2631 break;
2632 }
2633
2634 std::unique_ptr<LValue> lvalue;
2635 SpvId lhs;
John Stiles45990502021-02-16 10:55:27 -05002636 if (op.isAssignment()) {
John Stiles2396fb82021-03-25 11:44:55 -04002637 lvalue = this->getLValue(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002638 lhs = lvalue->load(out);
2639 } else {
2640 lvalue = nullptr;
John Stiles2396fb82021-03-25 11:44:55 -04002641 lhs = this->writeExpression(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002642 }
John Stiles2396fb82021-03-25 11:44:55 -04002643
John Stilesbc5c2a02021-04-08 11:44:53 -04002644 SpvId rhs;
2645 float rhsValue = division_by_literal_value(op, *right);
2646 if (rhsValue != 0.0f) {
2647 // Rewrite floating-point division by a literal into multiplication by the reciprocal.
2648 // This converts `expr / 2` into `expr * 0.5`
2649 // This improves codegen, especially for certain types of divides (e.g. vector/scalar).
2650 op = Operator(Token::Kind::TK_STAR);
2651 FloatLiteral reciprocal{right->fOffset, 1.0f / rhsValue, &right->type()};
2652 rhs = this->writeExpression(reciprocal, out);
2653 } else {
2654 // Write the right-hand side expression normally.
John Stiles2396fb82021-03-25 11:44:55 -04002655 rhs = this->writeExpression(*right, out);
2656 }
2657
2658 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
2659 right->type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002660 if (lvalue) {
2661 lvalue->store(result, out);
2662 }
2663 return result;
2664}
2665
John Stilesbc5c2a02021-04-08 11:44:53 -04002666SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
2667 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002668 BoolLiteral falseLiteral(/*offset=*/-1, /*value=*/false, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002669 SpvId falseConstant = this->writeBoolLiteral(falseLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002670 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002671 SpvId rhsLabel = this->nextId(nullptr);
2672 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002673 SpvId lhsBlock = fCurrentBlock;
2674 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2675 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2676 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002677 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002678 SpvId rhsBlock = fCurrentBlock;
2679 this->writeInstruction(SpvOpBranch, end, out);
2680 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002681 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002682 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002683 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002684 return result;
2685}
2686
John Stilesbc5c2a02021-04-08 11:44:53 -04002687SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
2688 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002689 BoolLiteral trueLiteral(/*offset=*/-1, /*value=*/true, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002690 SpvId trueConstant = this->writeBoolLiteral(trueLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002691 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002692 SpvId rhsLabel = this->nextId(nullptr);
2693 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002694 SpvId lhsBlock = fCurrentBlock;
2695 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2696 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2697 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002698 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002699 SpvId rhsBlock = fCurrentBlock;
2700 this->writeInstruction(SpvOpBranch, end, out);
2701 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002702 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002703 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002704 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002705 return result;
2706}
2707
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002708SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002709 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002710 SpvId test = this->writeExpression(*t.test(), out);
2711 if (t.ifTrue()->type().columns() == 1 &&
2712 t.ifTrue()->isCompileTimeConstant() &&
2713 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002714 // both true and false are constants, can just use OpSelect
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002715 SpvId result = this->nextId(nullptr);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002716 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2717 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002718 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002719 out);
2720 return result;
2721 }
Greg Daniel64773e62016-11-22 09:44:03 -05002722 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002723 // Adreno. Switched to storing the result in a temp variable as glslang does.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002724 SpvId var = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002725 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002726 var, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002727 SpvId trueLabel = this->nextId(nullptr);
2728 SpvId falseLabel = this->nextId(nullptr);
2729 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002730 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2731 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2732 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002733 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002734 this->writeInstruction(SpvOpBranch, end, out);
2735 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002736 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002737 this->writeInstruction(SpvOpBranch, end, out);
2738 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002739 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002740 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002741 return result;
2742}
2743
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002744SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002745 const Type& type = p.type();
John Stiles45990502021-02-16 10:55:27 -05002746 if (p.getOperator().kind() == Token::Kind::TK_MINUS) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002747 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002748 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002749 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002750 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002751 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002752 } else if (is_signed(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002753 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2754 } else {
John Stileseada7bc2021-02-02 16:29:32 -05002755 SkDEBUGFAILF("unsupported prefix expression %s", p.description().c_str());
Brian Salomon23356442018-11-30 15:33:19 -05002756 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002757 return result;
2758 }
John Stiles45990502021-02-16 10:55:27 -05002759 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002760 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002761 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002762 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002763 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002764 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2765 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one,
Greg Daniel64773e62016-11-22 09:44:03 -05002766 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002767 out);
2768 lv->store(result, out);
2769 return result;
2770 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002771 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002772 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002773 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2774 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2775 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002776 lv->store(result, out);
2777 return result;
2778 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002779 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002780 SkASSERT(p.operand()->type().isBoolean());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002781 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002782 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2783 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002784 return result;
2785 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002786 case Token::Kind::TK_BITWISENOT: {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002787 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002788 this->writeInstruction(SpvOpNot, this->getType(type), result,
2789 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002790 return result;
2791 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002792 default:
John Stileseada7bc2021-02-02 16:29:32 -05002793 SkDEBUGFAILF("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002794 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002795 }
2796}
2797
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002798SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002799 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002800 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002801 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002802 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
John Stiles45990502021-02-16 10:55:27 -05002803 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002804 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002805 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002806 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2807 lv->store(temp, out);
2808 return result;
2809 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002810 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002811 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002812 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2813 lv->store(temp, out);
2814 return result;
2815 }
2816 default:
John Stileseada7bc2021-02-02 16:29:32 -05002817 SkDEBUGFAILF("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002818 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002819 }
2820}
2821
ethannicholasf789b382016-08-03 12:43:36 -07002822SpvId SPIRVCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002823 if (b.value()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002824 if (fBoolTrue == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002825 fBoolTrue = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002826 this->writeInstruction(SpvOpConstantTrue, this->getType(b.type()), fBoolTrue,
ethannicholasb3058bd2016-07-01 08:22:01 -07002827 fConstantBuffer);
2828 }
2829 return fBoolTrue;
2830 } else {
2831 if (fBoolFalse == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002832 fBoolFalse = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002833 this->writeInstruction(SpvOpConstantFalse, this->getType(b.type()), fBoolFalse,
ethannicholasb3058bd2016-07-01 08:22:01 -07002834 fConstantBuffer);
2835 }
2836 return fBoolFalse;
2837 }
2838}
2839
ethannicholasf789b382016-08-03 12:43:36 -07002840SpvId SPIRVCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002841 SPIRVNumberConstant key{i.value(), i.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002842 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2843 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002844 SpvId result = this->nextId(nullptr);
John Stilesacb091f2021-01-06 11:57:58 -05002845 this->writeInstruction(SpvOpConstant, this->getType(i.type()), result, (SpvId) i.value(),
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002846 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002847 iter->second = result;
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002848 }
John Stilesacb091f2021-01-06 11:57:58 -05002849 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002850}
2851
ethannicholasf789b382016-08-03 12:43:36 -07002852SpvId SPIRVCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002853 // Convert the float literal into its bit-representation.
2854 float value = f.value();
2855 uint32_t valueBits;
2856 static_assert(sizeof(valueBits) == sizeof(value));
2857 memcpy(&valueBits, &value, sizeof(value));
2858
2859 SPIRVNumberConstant key{valueBits, f.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002860 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2861 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002862 SpvId result = this->nextId(nullptr);
John Stilesbdc3d3c2021-01-06 18:41:40 -05002863 this->writeInstruction(SpvOpConstant, this->getType(f.type()), result, (SpvId) valueBits,
John Stiles8c578662020-06-01 15:32:47 +00002864 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002865 iter->second = result;
John Stiles8c578662020-06-01 15:32:47 +00002866 }
John Stilesacb091f2021-01-06 11:57:58 -05002867 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002868}
2869
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002870SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002871 SpvId result = fFunctionMap[&f];
John Stilesb5db4822021-01-21 13:04:40 -05002872 SpvId returnTypeId = this->getType(f.returnType());
2873 SpvId functionTypeId = this->getFunctionType(f);
2874 this->writeInstruction(SpvOpFunction, returnTypeId, result,
2875 SpvFunctionControlMaskNone, functionTypeId, out);
John Stilesf9e85512021-03-22 12:05:31 -04002876 String mangledName = f.mangledName();
2877 this->writeInstruction(SpvOpName,
2878 result,
2879 StringFragment(mangledName.c_str(), mangledName.size()),
2880 fNameBuffer);
2881 for (const Variable* parameter : f.parameters()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002882 SpvId id = this->nextId(nullptr);
John Stilesf9e85512021-03-22 12:05:31 -04002883 fVariableMap[parameter] = id;
2884 SpvId type = this->getPointerType(parameter->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002885 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2886 }
2887 return result;
2888}
2889
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002890SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2891 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002892 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002893 fCurrentBlock = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002894 this->writeLabel(this->nextId(nullptr), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002895 StringStream bodyBuffer;
John Stiles0693fb82021-01-22 18:27:52 -05002896 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002897 write_stringstream(fVariableBuffer, out);
John Stilese8da4d22021-03-24 09:19:45 -04002898 if (f.declaration().isMain()) {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002899 write_stringstream(fGlobalInitializersBuffer, out);
2900 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002901 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002902 if (fCurrentBlock) {
John Stiles2558c462021-03-16 17:49:20 -04002903 if (f.declaration().returnType().isVoid()) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002904 this->writeInstruction(SpvOpReturn, out);
2905 } else {
2906 this->writeInstruction(SpvOpUnreachable, out);
2907 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002908 }
2909 this->writeInstruction(SpvOpFunctionEnd, out);
2910 return result;
2911}
2912
2913void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2914 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002915 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002916 fDecorationBuffer);
2917 }
2918 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002919 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002920 fDecorationBuffer);
2921 }
2922 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002923 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002924 fDecorationBuffer);
2925 }
2926 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002927 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002928 fDecorationBuffer);
2929 }
Greg Daniel64773e62016-11-22 09:44:03 -05002930 if (layout.fInputAttachmentIndex >= 0) {
2931 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2932 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002933 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002934 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04002935 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN &&
Greg Daniele6ab9982018-08-22 13:56:32 +00002936 layout.fBuiltin != SK_IN_BUILTIN && layout.fBuiltin != SK_OUT_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002937 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002938 fDecorationBuffer);
2939 }
2940}
2941
2942void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2943 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002944 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002945 layout.fLocation, fDecorationBuffer);
2946 }
2947 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002948 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002949 layout.fBinding, fDecorationBuffer);
2950 }
2951 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002952 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002953 layout.fIndex, fDecorationBuffer);
2954 }
2955 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002956 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002957 layout.fSet, fDecorationBuffer);
2958 }
Greg Daniel64773e62016-11-22 09:44:03 -05002959 if (layout.fInputAttachmentIndex >= 0) {
2960 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
2961 layout.fInputAttachmentIndex, fDecorationBuffer);
2962 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002963 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002964 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07002965 layout.fBuiltin, fDecorationBuffer);
2966 }
2967}
2968
Brian Osman2a4c0fb2021-01-22 13:41:40 -05002969MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05002970 bool pushConstant = ((v.modifiers().fLayout.fFlags & Layout::kPushConstant_Flag) != 0);
Brian Osman58ee8982021-02-18 15:39:38 -05002971 return pushConstant ? MemoryLayout(MemoryLayout::k430_Standard) : fDefaultLayout;
Brian Osman2a4c0fb2021-01-22 13:41:40 -05002972}
2973
Ethan Nicholas81d15112018-07-13 12:48:50 -04002974static void update_sk_in_count(const Modifiers& m, int* outSkInCount) {
2975 switch (m.fLayout.fPrimitive) {
2976 case Layout::kPoints_Primitive:
2977 *outSkInCount = 1;
2978 break;
2979 case Layout::kLines_Primitive:
2980 *outSkInCount = 2;
2981 break;
2982 case Layout::kLinesAdjacency_Primitive:
2983 *outSkInCount = 4;
2984 break;
2985 case Layout::kTriangles_Primitive:
2986 *outSkInCount = 3;
2987 break;
2988 case Layout::kTrianglesAdjacency_Primitive:
2989 *outSkInCount = 6;
2990 break;
2991 default:
2992 return;
2993 }
2994}
2995
Stephen White88574972020-06-23 19:09:29 -04002996SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTHeight) {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05002997 MemoryLayout memoryLayout = this->memoryLayoutForVariable(intf.variable());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002998 SpvId result = this->nextId(nullptr);
John Stilesad2d4942020-12-11 16:55:58 -05002999 std::unique_ptr<Type> rtHeightStructType;
Ethan Nicholaseaf47882020-10-15 10:10:08 -04003000 const Type* type = &intf.variable().type();
John Stiles21f5f452020-11-30 09:57:59 -05003001 if (!MemoryLayout::LayoutIsSupported(*type)) {
John Stiles0023c0c2020-11-16 13:32:18 -05003002 fErrors.error(type->fOffset, "type '" + type->name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003003 return this->nextId(nullptr);
John Stiles0023c0c2020-11-16 13:32:18 -05003004 }
John Stiles9485b552021-01-27 11:47:00 -05003005 SpvStorageClass_ storageClass = get_storage_class(intf.variable(), SpvStorageClassFunction);
Stephen White88574972020-06-23 19:09:29 -04003006 if (fProgram.fInputs.fRTHeight && appendRTHeight) {
Greg Daniele6ab9982018-08-22 13:56:32 +00003007 SkASSERT(fRTHeightStructId == (SpvId) -1);
3008 SkASSERT(fRTHeightFieldIndex == (SpvId) -1);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003009 std::vector<Type::Field> fields = type->fields();
Greg Daniele6ab9982018-08-22 13:56:32 +00003010 fRTHeightStructId = result;
3011 fRTHeightFieldIndex = fields.size();
Jim Van Verthf3ec9832020-10-21 16:09:57 -04003012 fRTHeightStorageClass = storageClass;
John Stilesad2d4942020-12-11 16:55:58 -05003013 fields.emplace_back(Modifiers(), StringFragment(SKSL_RTHEIGHT_NAME),
John Stiles54e7c052021-01-11 14:22:36 -05003014 fContext.fTypes.fFloat.get());
John Stilesad2d4942020-12-11 16:55:58 -05003015 rtHeightStructType = Type::MakeStructType(type->fOffset, type->name(), std::move(fields));
3016 type = rtHeightStructType.get();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003017 }
Ethan Nicholas5226b772018-05-03 16:20:41 -04003018 SpvId typeId;
John Stiles9485b552021-01-27 11:47:00 -05003019 const Modifiers& intfModifiers = intf.variable().modifiers();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003020 if (intfModifiers.fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osman133724c2020-10-28 14:14:39 -04003021 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003022 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003023 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholas81d15112018-07-13 12:48:50 -04003024 update_sk_in_count(m, &fSkInCount);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003025 }
3026 }
John Stilesad2d4942020-12-11 16:55:58 -05003027 typeId = this->getType(
3028 *Type::MakeArrayType("sk_in", intf.variable().type().componentType(), fSkInCount),
3029 memoryLayout);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003030 } else {
3031 typeId = this->getType(*type, memoryLayout);
3032 }
Brian Osman58ee8982021-02-18 15:39:38 -05003033 if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00003034 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04003035 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003036 SpvId ptrType = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003037 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003038 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003039 Layout layout = intfModifiers.fLayout;
3040 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04003041 layout.fSet = 0;
3042 }
3043 this->writeLayout(layout, result);
Ethan Nicholaseaf47882020-10-15 10:10:08 -04003044 fVariableMap[&intf.variable()] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07003045 return result;
3046}
3047
John Stiles9485b552021-01-27 11:47:00 -05003048static bool is_dead(const Variable& var, const ProgramUsage* usage) {
Brian Osman010ce6a2020-10-19 16:34:10 -04003049 ProgramUsage::VariableCounts counts = usage->get(var);
3050 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07003051 return false;
3052 }
Brian Osmand1f3b972021-03-22 17:03:42 -04003053 // It's not entirely clear what the rules are for eliding interface variables. Generally, it
3054 // causes problems to elide them, even when they're dead.
3055 return !(var.modifiers().fFlags &
3056 (Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag));
Chris Dalton2284aab2019-11-15 11:02:24 -07003057}
3058
John Stilesdbd4e6f2021-02-16 13:29:15 -05003059void SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind, const VarDeclaration& varDecl) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003060 const Variable& var = varDecl.var();
John Stiles0ca2f592021-01-27 10:58:10 -05003061 // 9999 is a sentinel value used in our built-in modules that causes us to ignore these
3062 // declarations, beyond adding them to the symbol table.
3063 constexpr int kBuiltinIgnore = 9999;
3064 if (var.modifiers().fLayout.fBuiltin == kBuiltinIgnore) {
Brian Osmanc0213602020-10-06 14:43:32 -04003065 return;
3066 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003067 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
John Stilesdbd4e6f2021-02-16 13:29:15 -05003068 kind != ProgramKind::kFragment) {
John Stiles270cec22021-02-17 12:59:36 -05003069 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Osmanc0213602020-10-06 14:43:32 -04003070 return;
3071 }
Brian Osman010ce6a2020-10-19 16:34:10 -04003072 if (is_dead(var, fProgram.fUsage.get())) {
Brian Osmanc0213602020-10-06 14:43:32 -04003073 return;
3074 }
John Stiles0de76f72021-01-29 09:19:39 -05003075 SpvStorageClass_ storageClass = get_storage_class(var, SpvStorageClassPrivate);
John Stilese40d1662021-01-29 10:08:50 -05003076 if (storageClass == SpvStorageClassUniform) {
3077 // Top-level uniforms are emitted in writeUniformBuffer.
3078 fTopLevelUniforms.push_back(&varDecl);
3079 return;
3080 }
3081 const Type& type = var.type();
John Stilesd8fc95d2021-01-26 16:22:53 -05003082 Layout layout = var.modifiers().fLayout;
John Stilese40d1662021-01-29 10:08:50 -05003083 if (layout.fSet < 0 && storageClass == SpvStorageClassUniformConstant) {
John Stiles270cec22021-02-17 12:59:36 -05003084 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
Brian Osmanc0213602020-10-06 14:43:32 -04003085 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003086 SpvId id = this->nextId(&type);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003087 fVariableMap[&var] = id;
Brian Osmanc0213602020-10-06 14:43:32 -04003088 SpvId typeId;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003089 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osmanc0213602020-10-06 14:43:32 -04003090 typeId = this->getPointerType(
John Stilesad2d4942020-12-11 16:55:58 -05003091 *Type::MakeArrayType("sk_in", type.componentType(), fSkInCount),
Brian Osmanc0213602020-10-06 14:43:32 -04003092 storageClass);
3093 } else {
3094 typeId = this->getPointerType(type, storageClass);
3095 }
3096 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003097 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003098 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04003099 SkASSERT(!fCurrentBlock);
3100 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003101 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04003102 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
3103 fCurrentBlock = 0;
3104 }
John Stilesd8fc95d2021-01-26 16:22:53 -05003105 this->writeLayout(layout, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003106 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003107 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
3108 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003109 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003110 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
3111 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003112 }
3113}
3114
Brian Osmanc0213602020-10-06 14:43:32 -04003115void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003116 const Variable& var = varDecl.var();
Ethan Nicholas7f015882021-03-23 14:16:52 -04003117 SpvId id = this->nextId(&var.type());
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003118 fVariableMap[&var] = id;
3119 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04003120 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003121 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
3122 if (varDecl.value()) {
3123 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04003124 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003125 }
3126}
3127
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003128void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003129 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04003130 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04003131 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04003132 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003133 case Statement::Kind::kBlock:
John Stiles0693fb82021-01-22 18:27:52 -05003134 this->writeBlock(s.as<Block>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003135 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003136 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04003137 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003138 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003139 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04003140 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003141 break;
Brian Osmanc0213602020-10-06 14:43:32 -04003142 case Statement::Kind::kVarDeclaration:
3143 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003144 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003145 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04003146 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003147 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003148 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04003149 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003150 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003151 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04003152 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003153 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003154 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04003155 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003156 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003157 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07003158 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
3159 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003160 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07003161 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
3162 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003163 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07003164 this->writeInstruction(SpvOpKill, out);
3165 break;
3166 default:
John Stileseada7bc2021-02-02 16:29:32 -05003167 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003168 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003169 }
3170}
3171
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003172void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04003173 for (const std::unique_ptr<Statement>& stmt : b.children()) {
3174 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003175 }
3176}
3177
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003178void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003179 SpvId test = this->writeExpression(*stmt.test(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003180 SpvId ifTrue = this->nextId(nullptr);
3181 SpvId ifFalse = this->nextId(nullptr);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003182 if (stmt.ifFalse()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003183 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003184 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3185 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3186 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003187 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003188 if (fCurrentBlock) {
3189 this->writeInstruction(SpvOpBranch, end, out);
3190 }
3191 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003192 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003193 if (fCurrentBlock) {
3194 this->writeInstruction(SpvOpBranch, end, out);
3195 }
3196 this->writeLabel(end, out);
3197 } else {
3198 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3199 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3200 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003201 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003202 if (fCurrentBlock) {
3203 this->writeInstruction(SpvOpBranch, ifFalse, out);
3204 }
3205 this->writeLabel(ifFalse, out);
3206 }
3207}
3208
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003209void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003210 if (f.initializer()) {
3211 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003212 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003213 SpvId header = this->nextId(nullptr);
3214 SpvId start = this->nextId(nullptr);
3215 SpvId body = this->nextId(nullptr);
3216 SpvId next = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003217 fContinueTarget.push(next);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003218 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003219 fBreakTarget.push(end);
3220 this->writeInstruction(SpvOpBranch, header, out);
3221 this->writeLabel(header, out);
3222 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003223 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003224 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003225 if (f.test()) {
3226 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003227 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003228 } else {
3229 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003230 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003231 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003232 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003233 if (fCurrentBlock) {
3234 this->writeInstruction(SpvOpBranch, next, out);
3235 }
3236 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003237 if (f.next()) {
3238 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003239 }
3240 this->writeInstruction(SpvOpBranch, header, out);
3241 this->writeLabel(end, out);
3242 fBreakTarget.pop();
3243 fContinueTarget.pop();
3244}
3245
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003246void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003247 SpvId header = this->nextId(nullptr);
3248 SpvId start = this->nextId(nullptr);
3249 SpvId next = this->nextId(nullptr);
3250 SpvId continueTarget = this->nextId(nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003251 fContinueTarget.push(continueTarget);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003252 SpvId end = this->nextId(nullptr);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003253 fBreakTarget.push(end);
3254 this->writeInstruction(SpvOpBranch, header, out);
3255 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003256 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003257 this->writeInstruction(SpvOpBranch, start, out);
3258 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003259 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003260 if (fCurrentBlock) {
3261 this->writeInstruction(SpvOpBranch, next, out);
3262 }
3263 this->writeLabel(next, out);
John Stiles68072a42021-04-16 17:25:55 -04003264 this->writeInstruction(SpvOpBranch, continueTarget, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003265 this->writeLabel(continueTarget, out);
John Stiles68072a42021-04-16 17:25:55 -04003266 SpvId test = this->writeExpression(*d.test(), out);
3267 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003268 this->writeLabel(end, out);
3269 fBreakTarget.pop();
3270 fContinueTarget.pop();
3271}
3272
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003273void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003274 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003275 std::vector<SpvId> labels;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003276 SpvId end = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003277 SpvId defaultLabel = end;
3278 fBreakTarget.push(end);
3279 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003280 auto& cases = s.cases();
John Stilesb23a64b2021-03-11 08:27:59 -05003281 for (const std::unique_ptr<Statement>& stmt : cases) {
3282 const SwitchCase& c = stmt->as<SwitchCase>();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003283 SpvId label = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003284 labels.push_back(label);
John Stilesb23a64b2021-03-11 08:27:59 -05003285 if (c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003286 size += 2;
3287 } else {
3288 defaultLabel = label;
3289 }
3290 }
3291 labels.push_back(end);
3292 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3293 this->writeOpCode(SpvOpSwitch, size, out);
3294 this->writeWord(value, out);
3295 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003296 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003297 const SwitchCase& c = cases[i]->as<SwitchCase>();
3298 if (!c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003299 continue;
3300 }
John Stilesb23a64b2021-03-11 08:27:59 -05003301 this->writeWord(c.value()->as<IntLiteral>().value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003302 this->writeWord(labels[i], out);
3303 }
John Stiles2d4f9592020-10-30 10:29:12 -04003304 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003305 const SwitchCase& c = cases[i]->as<SwitchCase>();
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003306 this->writeLabel(labels[i], out);
John Stilesb23a64b2021-03-11 08:27:59 -05003307 this->writeStatement(*c.statement(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003308 if (fCurrentBlock) {
3309 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3310 }
3311 }
3312 this->writeLabel(end, out);
3313 fBreakTarget.pop();
3314}
3315
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003316void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003317 if (r.expression()) {
3318 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003319 out);
3320 } else {
3321 this->writeInstruction(SpvOpReturn, out);
3322 }
3323}
3324
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003325void SPIRVCodeGenerator::writeGeometryShaderExecutionMode(SpvId entryPoint, OutputStream& out) {
John Stiles270cec22021-02-17 12:59:36 -05003326 SkASSERT(fProgram.fConfig->fKind == ProgramKind::kGeometry);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003327 int invocations = 1;
Brian Osman133724c2020-10-28 14:14:39 -04003328 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003329 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003330 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003331 if (m.fFlags & Modifiers::kIn_Flag) {
3332 if (m.fLayout.fInvocations != -1) {
3333 invocations = m.fLayout.fInvocations;
3334 }
3335 SpvId input;
3336 switch (m.fLayout.fPrimitive) {
3337 case Layout::kPoints_Primitive:
3338 input = SpvExecutionModeInputPoints;
3339 break;
3340 case Layout::kLines_Primitive:
3341 input = SpvExecutionModeInputLines;
3342 break;
3343 case Layout::kLinesAdjacency_Primitive:
3344 input = SpvExecutionModeInputLinesAdjacency;
3345 break;
3346 case Layout::kTriangles_Primitive:
3347 input = SpvExecutionModeTriangles;
3348 break;
3349 case Layout::kTrianglesAdjacency_Primitive:
3350 input = SpvExecutionModeInputTrianglesAdjacency;
3351 break;
3352 default:
3353 input = 0;
3354 break;
3355 }
Ethan Nicholas81d15112018-07-13 12:48:50 -04003356 update_sk_in_count(m, &fSkInCount);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003357 if (input) {
3358 this->writeInstruction(SpvOpExecutionMode, entryPoint, input, out);
3359 }
3360 } else if (m.fFlags & Modifiers::kOut_Flag) {
3361 SpvId output;
3362 switch (m.fLayout.fPrimitive) {
3363 case Layout::kPoints_Primitive:
3364 output = SpvExecutionModeOutputPoints;
3365 break;
3366 case Layout::kLineStrip_Primitive:
3367 output = SpvExecutionModeOutputLineStrip;
3368 break;
3369 case Layout::kTriangleStrip_Primitive:
3370 output = SpvExecutionModeOutputTriangleStrip;
3371 break;
3372 default:
3373 output = 0;
3374 break;
3375 }
3376 if (output) {
3377 this->writeInstruction(SpvOpExecutionMode, entryPoint, output, out);
3378 }
3379 if (m.fLayout.fMaxVertices != -1) {
3380 this->writeInstruction(SpvOpExecutionMode, entryPoint,
3381 SpvExecutionModeOutputVertices, m.fLayout.fMaxVertices,
3382 out);
3383 }
3384 }
3385 }
3386 }
3387 this->writeInstruction(SpvOpExecutionMode, entryPoint, SpvExecutionModeInvocations,
3388 invocations, out);
3389}
3390
John Stilese40d1662021-01-29 10:08:50 -05003391// Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
3392static std::shared_ptr<SymbolTable> get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
3393 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
3394}
3395
John Stiles4d6310a2021-01-26 19:58:22 -05003396SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
3397 const FunctionDeclaration& main) {
3398 // Our goal is to synthesize a tiny helper function which looks like this:
3399 // void _entrypoint() { sk_FragColor = main(); }
3400
3401 // Fish a symbol table out of main().
John Stilese40d1662021-01-29 10:08:50 -05003402 std::shared_ptr<SymbolTable> symbolTable = get_top_level_symbol_table(main);
John Stiles4d6310a2021-01-26 19:58:22 -05003403
3404 // Get `sk_FragColor` as a writable reference.
3405 const Symbol* skFragColorSymbol = (*symbolTable)["sk_FragColor"];
3406 SkASSERT(skFragColorSymbol);
3407 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
3408 auto skFragColorRef = std::make_unique<VariableReference>(/*offset=*/-1, &skFragColorVar,
3409 VariableReference::RefKind::kWrite);
3410 // Synthesize a call to the `main()` function.
3411 if (main.returnType() != skFragColorRef->type()) {
3412 fErrors.error(main.fOffset, "SPIR-V does not support returning '" +
3413 main.returnType().description() + "' from main()");
3414 return {};
3415 }
Brian Osman716aeb92021-04-21 13:20:00 -04003416 ExpressionArray args;
3417 if (main.parameters().size() == 1) {
3418 if (main.parameters()[0]->type() != *fContext.fTypes.fFloat2) {
3419 fErrors.error(main.fOffset,
3420 "SPIR-V does not support parameter of type '" +
3421 main.parameters()[0]->type().description() + "' to main()");
3422 return {};
3423 }
3424 auto zero = std::make_unique<FloatLiteral>(
3425 /*offset=*/-1, 0.0f, fContext.fTypes.fFloatLiteral.get());
3426 auto zeros = std::make_unique<ConstructorSplat>(
3427 /*offset=*/-1, *fContext.fTypes.fFloat2, std::move(zero));
3428 args.push_back(std::move(zeros));
3429 }
John Stiles4d6310a2021-01-26 19:58:22 -05003430 auto callMainFn = std::make_unique<FunctionCall>(/*offset=*/-1, &main.returnType(), &main,
Brian Osman716aeb92021-04-21 13:20:00 -04003431 std::move(args));
John Stiles4d6310a2021-01-26 19:58:22 -05003432
3433 // Synthesize `skFragColor = main()` as a BinaryExpression.
3434 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
3435 /*offset=*/-1,
3436 std::move(skFragColorRef),
3437 Token::Kind::TK_EQ,
3438 std::move(callMainFn),
3439 &main.returnType()));
3440
3441 // Function bodies are always wrapped in a Block.
3442 StatementArray entrypointStmts;
3443 entrypointStmts.push_back(std::move(assignmentStmt));
John Stilesbf16b6c2021-03-12 19:24:31 -05003444 auto entrypointBlock = Block::Make(/*offset=*/-1, std::move(entrypointStmts),
3445 symbolTable, /*isScope=*/true);
John Stiles4d6310a2021-01-26 19:58:22 -05003446 // Declare an entrypoint function.
3447 EntrypointAdapter adapter;
3448 adapter.fLayout = {};
3449 adapter.fModifiers = Modifiers{adapter.fLayout, Modifiers::kHasSideEffects_Flag};
3450 adapter.entrypointDecl =
3451 std::make_unique<FunctionDeclaration>(/*offset=*/-1,
3452 &adapter.fModifiers,
3453 "_entrypoint",
3454 /*parameters=*/std::vector<const Variable*>{},
3455 /*returnType=*/fContext.fTypes.fVoid.get(),
3456 /*builtin=*/false);
3457 // Define it.
3458 adapter.entrypointDef =
3459 std::make_unique<FunctionDefinition>(/*offset=*/-1, adapter.entrypointDecl.get(),
3460 /*builtin=*/false,
3461 /*body=*/std::move(entrypointBlock));
3462
3463 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
3464 return adapter;
3465}
3466
John Stilese40d1662021-01-29 10:08:50 -05003467void SPIRVCodeGenerator::writeUniformBuffer(std::shared_ptr<SymbolTable> topLevelSymbolTable) {
3468 SkASSERT(!fTopLevelUniforms.empty());
3469 static constexpr char kUniformBufferName[] = "_UniformBuffer";
3470
3471 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
3472 // a lookup table of variables to UniformBuffer field indices.
3473 std::vector<Type::Field> fields;
3474 fields.reserve(fTopLevelUniforms.size());
3475 fTopLevelUniformMap.reserve(fTopLevelUniforms.size());
3476 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
3477 const Variable* var = &topLevelUniform->var();
3478 fTopLevelUniformMap[var] = (int)fields.size();
3479 fields.emplace_back(var->modifiers(), var->name(), &var->type());
3480 }
3481 fUniformBuffer.fStruct = Type::MakeStructType(/*offset=*/-1, kUniformBufferName,
3482 std::move(fields));
3483
3484 // Create a global variable to contain this struct.
3485 Layout layout;
John Stiles270cec22021-02-17 12:59:36 -05003486 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
3487 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilese40d1662021-01-29 10:08:50 -05003488 Modifiers modifiers{layout, Modifiers::kUniform_Flag};
3489
3490 fUniformBuffer.fInnerVariable = std::make_unique<Variable>(
John Stilesf2872e62021-05-04 11:38:43 -04003491 /*offset=*/-1, fProgram.fModifiers->add(modifiers), kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003492 fUniformBuffer.fStruct.get(), /*builtin=*/false, Variable::Storage::kGlobal);
3493
3494 // Create an interface block object for this global variable.
3495 fUniformBuffer.fInterfaceBlock = std::make_unique<InterfaceBlock>(
3496 /*offset=*/-1, fUniformBuffer.fInnerVariable.get(), kUniformBufferName,
3497 kUniformBufferName, /*arraySize=*/0, topLevelSymbolTable);
3498
3499 // Generate an interface block and hold onto its ID.
3500 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
3501}
3502
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003503void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003504 fGLSLExtendedInstructions = this->nextId(nullptr);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003505 StringStream body;
John Stiles4d6310a2021-01-26 19:58:22 -05003506 // Assign SpvIds to functions.
3507 const FunctionDeclaration* main = nullptr;
Brian Osman133724c2020-10-28 14:14:39 -04003508 for (const ProgramElement* e : program.elements()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003509 if (e->is<FunctionDefinition>()) {
3510 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
3511 const FunctionDeclaration& funcDecl = funcDef.declaration();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003512 fFunctionMap[&funcDecl] = this->nextId(nullptr);
John Stilese8da4d22021-03-24 09:19:45 -04003513 if (funcDecl.isMain()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003514 main = &funcDecl;
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003515 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003516 }
3517 }
John Stiles4d6310a2021-01-26 19:58:22 -05003518 // Make sure we have a main() function.
3519 if (!main) {
3520 fErrors.error(/*offset=*/0, "program does not contain a main() function");
3521 return;
3522 }
3523 // Emit interface blocks.
3524 std::set<SpvId> interfaceVars;
Brian Osman133724c2020-10-28 14:14:39 -04003525 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003526 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003527 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003528 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003529
3530 const Modifiers& modifiers = intf.variable().modifiers();
John Stiles8e2a84b2021-04-19 09:35:38 -04003531 if ((modifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003532 modifiers.fLayout.fBuiltin == -1 &&
Brian Osman010ce6a2020-10-19 16:34:10 -04003533 !is_dead(intf.variable(), fProgram.fUsage.get())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003534 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003535 }
3536 }
3537 }
John Stiles4d6310a2021-01-26 19:58:22 -05003538 // Emit global variable declarations.
Brian Osman133724c2020-10-28 14:14:39 -04003539 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003540 if (e->is<GlobalVarDeclaration>()) {
John Stiles270cec22021-02-17 12:59:36 -05003541 this->writeGlobalVar(program.fConfig->fKind,
John Stilese40d1662021-01-29 10:08:50 -05003542 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07003543 }
3544 }
John Stilese40d1662021-01-29 10:08:50 -05003545 // Emit top-level uniforms into a dedicated uniform buffer.
3546 if (!fTopLevelUniforms.empty()) {
3547 this->writeUniformBuffer(get_top_level_symbol_table(*main));
3548 }
John Stiles4d6310a2021-01-26 19:58:22 -05003549 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
3550 // main() and stores the result into sk_FragColor.
3551 EntrypointAdapter adapter;
3552 if (main->returnType() == *fContext.fTypes.fHalf4) {
3553 adapter = this->writeEntrypointAdapter(*main);
3554 if (adapter.entrypointDecl) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003555 fFunctionMap[adapter.entrypointDecl.get()] = this->nextId(nullptr);
John Stiles4d6310a2021-01-26 19:58:22 -05003556 this->writeFunction(*adapter.entrypointDef, body);
3557 main = adapter.entrypointDecl.get();
3558 }
3559 }
3560 // Emit all the functions.
Brian Osman133724c2020-10-28 14:14:39 -04003561 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003562 if (e->is<FunctionDefinition>()) {
3563 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003564 }
3565 }
John Stiles4d6310a2021-01-26 19:58:22 -05003566 // Add global in/out variables to the list of interface variables.
ethannicholasb3058bd2016-07-01 08:22:01 -07003567 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003568 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003569 if (var->storage() == Variable::Storage::kGlobal &&
John Stiles8e2a84b2021-04-19 09:35:38 -04003570 (var->modifiers().fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
Brian Osman010ce6a2020-10-19 16:34:10 -04003571 !is_dead(*var, fProgram.fUsage.get())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003572 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003573 }
3574 }
3575 this->writeCapabilities(out);
3576 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3577 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholase2c49992020-10-05 11:49:11 -04003578 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().fLength + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003579 (int32_t) interfaceVars.size(), out);
John Stiles270cec22021-02-17 12:59:36 -05003580 switch (program.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05003581 case ProgramKind::kVertex:
ethannicholasb3058bd2016-07-01 08:22:01 -07003582 this->writeWord(SpvExecutionModelVertex, out);
3583 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003584 case ProgramKind::kFragment:
ethannicholasb3058bd2016-07-01 08:22:01 -07003585 this->writeWord(SpvExecutionModelFragment, out);
3586 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003587 case ProgramKind::kGeometry:
Ethan Nicholas52cad152017-02-16 16:37:32 -05003588 this->writeWord(SpvExecutionModelGeometry, out);
3589 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003590 default:
John Stilesf57207b2021-02-02 17:50:34 -05003591 SK_ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003592 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003593 SpvId entryPoint = fFunctionMap[main];
3594 this->writeWord(entryPoint, out);
Ethan Nicholase2c49992020-10-05 11:49:11 -04003595 this->writeString(main->name().fChars, main->name().fLength, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003596 for (int var : interfaceVars) {
3597 this->writeWord(var, out);
3598 }
John Stiles270cec22021-02-17 12:59:36 -05003599 if (program.fConfig->fKind == ProgramKind::kGeometry) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003600 this->writeGeometryShaderExecutionMode(entryPoint, out);
3601 }
John Stiles270cec22021-02-17 12:59:36 -05003602 if (program.fConfig->fKind == ProgramKind::kFragment) {
Greg Daniel64773e62016-11-22 09:44:03 -05003603 this->writeInstruction(SpvOpExecutionMode,
3604 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003605 SpvExecutionModeOriginUpperLeft,
3606 out);
3607 }
Brian Osman133724c2020-10-28 14:14:39 -04003608 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003609 if (e->is<Extension>()) {
3610 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name().c_str(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003611 }
3612 }
Greg Daniel64773e62016-11-22 09:44:03 -05003613
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003614 write_stringstream(fExtraGlobalsBuffer, out);
3615 write_stringstream(fNameBuffer, out);
3616 write_stringstream(fDecorationBuffer, out);
3617 write_stringstream(fConstantBuffer, out);
3618 write_stringstream(fExternalFunctionsBuffer, out);
3619 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003620}
3621
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003622bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04003623 SkASSERT(!fErrors.errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003624 this->writeWord(SpvMagicNumber, *fOut);
3625 this->writeWord(SpvVersion, *fOut);
3626 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003627 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003628 this->writeInstructions(fProgram, buffer);
3629 this->writeWord(fIdCount, *fOut);
3630 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003631 write_stringstream(buffer, *fOut);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003632 return 0 == fErrors.errorCount();
ethannicholasb3058bd2016-07-01 08:22:01 -07003633}
3634
John Stilesa6841be2020-08-06 14:11:56 -04003635} // namespace SkSL