blob: 26bba9b05ad2f542428a9e2abafd015e86213fd4 [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 Stilesf2b08cc2021-05-17 14:46:05 -0400208 if (fCurrentBlock == 0) {
209 // We just encountered dead code--instructions that don't have an associated block.
210 // Synthesize a label if this happens; this is necessary to satisfy the validator.
211 this->writeLabel(this->nextId(nullptr), out);
212 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700213 fCurrentBlock = 0;
214 break;
215 case SpvOpConstant: // fall through
216 case SpvOpConstantTrue: // fall through
217 case SpvOpConstantFalse: // fall through
218 case SpvOpConstantComposite: // fall through
219 case SpvOpTypeVoid: // fall through
220 case SpvOpTypeInt: // fall through
221 case SpvOpTypeFloat: // fall through
222 case SpvOpTypeBool: // fall through
223 case SpvOpTypeVector: // fall through
224 case SpvOpTypeMatrix: // fall through
225 case SpvOpTypeArray: // fall through
226 case SpvOpTypePointer: // fall through
227 case SpvOpTypeFunction: // fall through
228 case SpvOpTypeRuntimeArray: // fall through
229 case SpvOpTypeStruct: // fall through
230 case SpvOpTypeImage: // fall through
231 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400232 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700233 case SpvOpVariable: // fall through
234 case SpvOpFunction: // fall through
235 case SpvOpFunctionParameter: // fall through
236 case SpvOpFunctionEnd: // fall through
237 case SpvOpExecutionMode: // fall through
238 case SpvOpMemoryModel: // fall through
239 case SpvOpCapability: // fall through
240 case SpvOpExtInstImport: // fall through
241 case SpvOpEntryPoint: // fall through
242 case SpvOpSource: // fall through
243 case SpvOpSourceExtension: // fall through
244 case SpvOpName: // fall through
245 case SpvOpMemberName: // fall through
246 case SpvOpDecorate: // fall through
247 case SpvOpMemberDecorate:
248 break;
249 default:
John Stilesf3a28db2021-03-10 23:00:47 -0500250 // We may find ourselves with dead code--instructions that don't have an associated
251 // block. This should be a rare event, but if it happens, synthesize a label; this is
252 // necessary to satisfy the validator.
253 if (fCurrentBlock == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400254 this->writeLabel(this->nextId(nullptr), out);
John Stiles7142e402021-02-23 12:28:18 -0500255 }
John Stiles453f1432021-02-25 16:58:04 -0500256 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700257 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700258 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700259}
260
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400261void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500262 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700263 fCurrentBlock = label;
264 this->writeInstruction(SpvOpLabel, label, out);
265}
266
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400267void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700268 this->writeOpCode(opCode, 1, out);
269}
270
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400271void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700272 this->writeOpCode(opCode, 2, out);
273 this->writeWord(word1, out);
274}
275
Ethan Nicholas962dec42021-06-10 13:06:39 -0400276void SPIRVCodeGenerator::writeString(skstd::string_view s, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400277 out.write(s.data(), s.length());
278 switch (s.length() % 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700279 case 1:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500280 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400281 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700282 case 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500283 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400284 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700285 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500286 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700287 break;
288 default:
289 this->writeWord(0, out);
290 }
291}
292
Ethan Nicholas962dec42021-06-10 13:06:39 -0400293void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, skstd::string_view string,
294 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400295 this->writeOpCode(opCode, 1 + (string.length() + 4) / 4, out);
296 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700297}
298
299
Ethan Nicholas962dec42021-06-10 13:06:39 -0400300void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, skstd::string_view string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400301 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400302 this->writeOpCode(opCode, 2 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700303 this->writeWord(word1, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400304 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700305}
306
Greg Daniel64773e62016-11-22 09:44:03 -0500307void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400308 skstd::string_view string, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400309 this->writeOpCode(opCode, 3 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700310 this->writeWord(word1, out);
311 this->writeWord(word2, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400312 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700313}
314
Greg Daniel64773e62016-11-22 09:44:03 -0500315void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400316 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700317 this->writeOpCode(opCode, 3, out);
318 this->writeWord(word1, out);
319 this->writeWord(word2, out);
320}
321
Greg Daniel64773e62016-11-22 09:44:03 -0500322void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400323 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700324 this->writeOpCode(opCode, 4, out);
325 this->writeWord(word1, out);
326 this->writeWord(word2, out);
327 this->writeWord(word3, out);
328}
329
Greg Daniel64773e62016-11-22 09:44:03 -0500330void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400331 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700332 this->writeOpCode(opCode, 5, out);
333 this->writeWord(word1, out);
334 this->writeWord(word2, out);
335 this->writeWord(word3, out);
336 this->writeWord(word4, out);
337}
338
Greg Daniel64773e62016-11-22 09:44:03 -0500339void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
340 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400341 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700342 this->writeOpCode(opCode, 6, out);
343 this->writeWord(word1, out);
344 this->writeWord(word2, out);
345 this->writeWord(word3, out);
346 this->writeWord(word4, out);
347 this->writeWord(word5, out);
348}
349
Greg Daniel64773e62016-11-22 09:44:03 -0500350void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700351 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400352 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700353 this->writeOpCode(opCode, 7, out);
354 this->writeWord(word1, out);
355 this->writeWord(word2, out);
356 this->writeWord(word3, out);
357 this->writeWord(word4, out);
358 this->writeWord(word5, out);
359 this->writeWord(word6, out);
360}
361
Greg Daniel64773e62016-11-22 09:44:03 -0500362void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700363 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400364 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700365 this->writeOpCode(opCode, 8, out);
366 this->writeWord(word1, out);
367 this->writeWord(word2, out);
368 this->writeWord(word3, out);
369 this->writeWord(word4, out);
370 this->writeWord(word5, out);
371 this->writeWord(word6, out);
372 this->writeWord(word7, out);
373}
374
Greg Daniel64773e62016-11-22 09:44:03 -0500375void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700376 int32_t word3, int32_t word4, int32_t word5,
377 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400378 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700379 this->writeOpCode(opCode, 9, out);
380 this->writeWord(word1, out);
381 this->writeWord(word2, out);
382 this->writeWord(word3, out);
383 this->writeWord(word4, out);
384 this->writeWord(word5, out);
385 this->writeWord(word6, out);
386 this->writeWord(word7, out);
387 this->writeWord(word8, out);
388}
389
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400390void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700391 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
392 if (fCapabilities & bit) {
393 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
394 }
395 }
John Stiles270cec22021-02-17 12:59:36 -0500396 if (fProgram.fConfig->fKind == ProgramKind::kGeometry) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400397 this->writeInstruction(SpvOpCapability, SpvCapabilityGeometry, out);
398 }
Ethan Nicholas81d15112018-07-13 12:48:50 -0400399 else {
400 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
401 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700402}
403
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400404SpvId SPIRVCodeGenerator::nextId(const Type* type) {
405 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
406 ? Precision::kRelaxed
407 : Precision::kDefault);
408}
409
410SpvId SPIRVCodeGenerator::nextId(Precision precision) {
411 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
412 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
413 fDecorationBuffer);
414 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700415 return fIdCount++;
416}
417
Ethan Nicholas19671772016-11-28 16:30:17 -0500418void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
419 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400420 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700421 // go ahead and write all of the field types, so we don't inadvertently write them while we're
422 // in the middle of writing the struct instruction
423 std::vector<SpvId> types;
424 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500425 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700426 }
427 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
428 this->writeWord(resultId, fConstantBuffer);
429 for (SpvId id : types) {
430 this->writeWord(id, fConstantBuffer);
431 }
432 size_t offset = 0;
433 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400434 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500435 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
John Stiles0023c0c2020-11-16 13:32:18 -0500436 fErrors.error(type.fOffset, "type '" + field.fType->name() + "' is not permitted here");
437 return;
438 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400439 size_t size = memoryLayout.size(*field.fType);
440 size_t alignment = memoryLayout.alignment(*field.fType);
441 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500442 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500443 if (fieldLayout.fOffset < (int) offset) {
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 at "
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500446 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500447 }
448 if (fieldLayout.fOffset % alignment) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700449 fErrors.error(type.fOffset,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400450 "offset of field '" + field.fName + "' must be a multiple"
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500451 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500452 }
453 offset = fieldLayout.fOffset;
454 } else {
455 size_t mod = offset % alignment;
456 if (mod) {
457 offset += alignment - mod;
458 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700459 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400460 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500461 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400462 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500463 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700464 (SpvId) offset, fDecorationBuffer);
465 }
John Stiles9aeed132020-11-24 17:36:06 -0500466 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500467 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700468 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500469 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400470 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800471 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700472 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400473 if (!field.fType->highPrecision()) {
474 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
475 SpvDecorationRelaxedPrecision, fDecorationBuffer);
476 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700477 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500478 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700479 offset += alignment - offset % alignment;
480 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700481 }
482}
483
Ethan Nicholase2c49992020-10-05 11:49:11 -0400484const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500485 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500486 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400487 }
John Stiles4c151702021-02-09 18:31:34 -0500488 if (type.isSigned() || type.isEnum()) {
John Stiles54e7c052021-01-11 14:22:36 -0500489 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400490 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500491 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500492 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400493 }
John Stiles9aeed132020-11-24 17:36:06 -0500494 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500495 if (type.componentType() == *fContext.fTypes.fHalf) {
496 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400497 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400498 if (type.componentType() == *fContext.fTypes.fShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500499 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400500 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400501 if (type.componentType() == *fContext.fTypes.fUShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500502 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400503 }
504 }
505 return type;
506}
507
ethannicholasb3058bd2016-07-01 08:22:01 -0700508SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800509 return this->getType(type, fDefaultLayout);
510}
511
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400512SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400513 const Type& type = this->getActualType(rawType);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400514 String key(type.name());
John Stilesc0c51062020-12-03 17:16:29 -0500515 if (type.isStruct() || type.isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400516 key += to_string((int)layout.fStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500517#ifdef SK_DEBUG
518 SkASSERT(layout.fStd == MemoryLayout::Standard::k140_Standard ||
519 layout.fStd == MemoryLayout::Standard::k430_Standard);
520 MemoryLayout::Standard otherStd = layout.fStd == MemoryLayout::Standard::k140_Standard
521 ? MemoryLayout::Standard::k430_Standard
522 : MemoryLayout::Standard::k140_Standard;
523 String otherKey = type.name() + to_string((int)otherStd);
524 SkASSERT(fTypeMap.find(otherKey) == fTypeMap.end());
525#endif
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400526 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800527 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700528 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400529 SpvId result = this->nextId(nullptr);
Ethan Nicholase6592142020-09-08 10:22:09 -0400530 switch (type.typeKind()) {
531 case Type::TypeKind::kScalar:
John Stiles4a7dc462020-11-25 11:08:08 -0500532 if (type.isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700533 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500534 } else if (type == *fContext.fTypes.fInt || type == *fContext.fTypes.fShort ||
535 type == *fContext.fTypes.fIntLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700536 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500537 } else if (type == *fContext.fTypes.fUInt || type == *fContext.fTypes.fUShort) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700538 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500539 } else if (type == *fContext.fTypes.fFloat || type == *fContext.fTypes.fHalf ||
540 type == *fContext.fTypes.fFloatLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700541 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700542 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400543 SkASSERT(false);
ethannicholasb3058bd2016-07-01 08:22:01 -0700544 }
545 break;
John Stilesfd41d872020-11-25 22:39:45 -0500546 case Type::TypeKind::kEnum:
547 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
548 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400549 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500550 this->writeInstruction(SpvOpTypeVector, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800551 this->getType(type.componentType(), layout),
ethannicholasb3058bd2016-07-01 08:22:01 -0700552 type.columns(), fConstantBuffer);
553 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400554 case Type::TypeKind::kMatrix:
John Stiles51d33982021-03-08 09:18:07 -0500555 this->writeInstruction(
556 SpvOpTypeMatrix,
557 result,
558 this->getType(IndexExpression::IndexType(fContext, type), layout),
559 type.columns(),
560 fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700561 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400562 case Type::TypeKind::kStruct:
ethannicholas8ac838d2016-11-22 08:39:36 -0800563 this->writeStruct(type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700564 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400565 case Type::TypeKind::kArray: {
John Stiles21f5f452020-11-30 09:57:59 -0500566 if (!MemoryLayout::LayoutIsSupported(type)) {
567 fErrors.error(type.fOffset, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400568 return this->nextId(nullptr);
John Stiles21f5f452020-11-30 09:57:59 -0500569 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700570 if (type.columns() > 0) {
John Stilesb5db4822021-01-21 13:04:40 -0500571 SpvId typeId = this->getType(type.componentType(), layout);
John Stiles9ce80f72021-03-11 22:35:19 -0500572 IntLiteral countLiteral(/*offset=*/-1, type.columns(),
573 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -0500574 SpvId countId = this->writeIntLiteral(countLiteral);
575 this->writeInstruction(SpvOpTypeArray, result, typeId, countId,
576 fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500577 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400578 (int32_t) layout.stride(type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800579 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700580 } else {
John Stiles5570c512020-11-19 17:58:07 -0500581 // We shouldn't have any runtime-sized arrays right now
582 fErrors.error(type.fOffset, "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500583 this->writeInstruction(SpvOpTypeRuntimeArray, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800584 this->getType(type.componentType(), layout),
585 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400586 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
587 (int32_t) layout.stride(type),
588 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700589 }
590 break;
591 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400592 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500593 SpvId image = result;
594 if (SpvDimSubpassData != type.dimensions()) {
Stephen White792e2302019-08-09 13:33:51 -0400595 image = this->getType(type.textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500596 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400597 if (SpvDimBuffer == type.dimensions()) {
598 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
599 }
Greg Daniel64773e62016-11-22 09:44:03 -0500600 if (SpvDimSubpassData != type.dimensions()) {
601 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
602 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700603 break;
604 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400605 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400606 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
607 break;
608 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400609 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400610 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500611 this->getType(*fContext.fTypes.fFloat, layout),
John Stilesc0c51062020-12-03 17:16:29 -0500612 type.dimensions(), type.isDepth(), type.isArrayedTexture(),
Stephen White792e2302019-08-09 13:33:51 -0400613 type.isMultisampled(), type.isSampled() ? 1 : 2,
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400614 SpvImageFormatUnknown, fConstantBuffer);
615 fImageTypeMap[key] = result;
616 break;
617 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700618 default:
John Stiles2558c462021-03-16 17:49:20 -0400619 if (type.isVoid()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700620 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
621 } else {
John Stileseada7bc2021-02-02 16:29:32 -0500622 SkDEBUGFAILF("invalid type: %s", type.description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700623 }
624 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800625 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700626 return result;
627 }
628 return entry->second;
629}
630
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400631SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400632 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400633 this->getType(type);
634 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400635 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400636 return fImageTypeMap[key];
637}
638
ethannicholasd598f792016-07-25 10:08:54 -0700639SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400640 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400641 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400642 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400643 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700644 key += separator;
645 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400646 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700647 }
648 key += ")";
649 auto entry = fTypeMap.find(key);
650 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400651 SpvId result = this->nextId(nullptr);
Ethan Nicholased84b732020-10-08 11:45:44 -0400652 int32_t length = 3 + (int32_t) parameters.size();
653 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700654 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400655 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500656 // glslang seems to treat all function arguments as pointers whether they need to be or
657 // not. I was initially puzzled by this until I ran bizarre failures with certain
658 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700659 // failure case:
660 //
661 // void sphere(float x) {
662 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500663 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700664 // void map() {
665 // sphere(1.0);
666 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500667 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700668 // void main() {
669 // for (int i = 0; i < 1; i++) {
670 // map();
671 // }
672 // }
673 //
Greg Daniel64773e62016-11-22 09:44:03 -0500674 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
675 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700676 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
677 // the spec makes this make sense.
678// if (is_out(function->fParameters[i])) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400679 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
ethannicholasb3058bd2016-07-01 08:22:01 -0700680 SpvStorageClassFunction));
681// } else {
ethannicholasd598f792016-07-25 10:08:54 -0700682// parameterTypes.push_back(this->getType(function.fParameters[i]->fType));
ethannicholasb3058bd2016-07-01 08:22:01 -0700683// }
684 }
685 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
686 this->writeWord(result, fConstantBuffer);
687 this->writeWord(returnType, fConstantBuffer);
688 for (SpvId id : parameterTypes) {
689 this->writeWord(id, fConstantBuffer);
690 }
691 fTypeMap[key] = result;
692 return result;
693 }
694 return entry->second;
695}
696
ethannicholas8ac838d2016-11-22 08:39:36 -0800697SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
698 return this->getPointerType(type, fDefaultLayout, storageClass);
699}
700
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400701SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700702 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400703 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500704 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700705 auto entry = fTypeMap.find(key);
706 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400707 SpvId result = this->nextId(nullptr);
Greg Daniel64773e62016-11-22 09:44:03 -0500708 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700709 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700710 fTypeMap[key] = result;
711 return result;
712 }
713 return entry->second;
714}
715
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400716SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400717 switch (expr.kind()) {
718 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400719 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400720 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400721 return this->writeBoolLiteral(expr.as<BoolLiteral>());
John Stiles7384b372021-04-01 13:48:15 -0400722 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400723 case Expression::Kind::kConstructorStruct:
724 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
John Stilese1182782021-03-30 22:09:37 -0400725 case Expression::Kind::kConstructorDiagonalMatrix:
726 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
John Stiles5abb9e12021-04-06 13:47:19 -0400727 case Expression::Kind::kConstructorMatrixResize:
728 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
John Stilesfd7252f2021-04-04 22:24:40 -0400729 case Expression::Kind::kConstructorScalarCast:
730 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
John Stiles2938eea2021-04-01 18:58:25 -0400731 case Expression::Kind::kConstructorSplat:
732 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
John Stiles8cad6372021-04-07 12:31:13 -0400733 case Expression::Kind::kConstructorCompound:
734 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
735 case Expression::Kind::kConstructorCompoundCast:
736 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400737 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400738 return this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400739 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400740 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400741 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400742 return this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400743 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400744 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400745 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400746 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400747 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400748 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400749 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400750 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400751 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400752 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400753 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400754 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400755 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400756 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700757 default:
John Stileseada7bc2021-02-02 16:29:32 -0500758 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500759 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700760 }
761 return -1;
762}
763
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400764SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400765 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -0400766 auto intrinsic = fIntrinsicMap.find(function.intrinsicKind());
John Stiles93e661a2020-12-08 16:17:00 -0500767 if (intrinsic == fIntrinsicMap.end()) {
768 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
769 return -1;
770 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700771 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500772 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400773 if (arguments.size() > 0) {
774 const Type& type = arguments[0]->type();
John Stilesaaac4e42021-05-06 14:08:28 -0400775 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicOpcodeKind ||
776 is_float(fContext, type)) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400777 intrinsicId = std::get<1>(intrinsic->second);
778 } else if (is_signed(fContext, type)) {
779 intrinsicId = std::get<2>(intrinsic->second);
780 } else if (is_unsigned(fContext, type)) {
781 intrinsicId = std::get<3>(intrinsic->second);
782 } else if (is_bool(fContext, type)) {
783 intrinsicId = std::get<4>(intrinsic->second);
784 } else {
785 intrinsicId = std::get<1>(intrinsic->second);
786 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700787 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400788 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700789 }
790 switch (std::get<0>(intrinsic->second)) {
John Stilesaaac4e42021-05-06 14:08:28 -0400791 case kGLSL_STD_450_IntrinsicOpcodeKind: {
Ethan Nicholas7f015882021-03-23 14:16:52 -0400792 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400793 std::vector<SpvId> argumentIds;
794 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400795 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500796 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400797 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400798 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400799 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400800 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700801 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400802 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400803 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700804 this->writeWord(result, out);
805 this->writeWord(fGLSLExtendedInstructions, out);
806 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400807 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700808 this->writeWord(id, out);
809 }
810 return result;
811 }
John Stilesaaac4e42021-05-06 14:08:28 -0400812 case kSPIRV_IntrinsicOpcodeKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500813 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500814 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500815 intrinsicId = SpvOpFMul;
816 }
Ethan Nicholas7f015882021-03-23 14:16:52 -0400817 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400818 std::vector<SpvId> argumentIds;
819 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400820 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500821 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400822 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400823 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400824 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400825 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700826 }
John Stiles2558c462021-03-16 17:49:20 -0400827 if (!c.type().isVoid()) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400828 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400829 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400830 this->writeWord(result, out);
831 } else {
832 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
833 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400834 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700835 this->writeWord(id, out);
836 }
837 return result;
838 }
John Stilesaaac4e42021-05-06 14:08:28 -0400839 case kSpecial_IntrinsicOpcodeKind:
ethannicholasb3058bd2016-07-01 08:22:01 -0700840 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
841 default:
John Stiles93e661a2020-12-08 16:17:00 -0500842 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
843 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700844 }
845}
846
John Stiles8e3b6be2020-10-13 11:14:08 -0400847std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500848 int vectorSize = 0;
849 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500850 if (a->type().isVector()) {
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500851 if (vectorSize) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400852 SkASSERT(a->type().columns() == vectorSize);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500853 }
854 else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400855 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500856 }
857 }
858 }
859 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400860 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400861 for (const auto& arg : args) {
862 const Type& argType = arg->type();
Robert Phillipsc650cc02021-05-14 14:29:23 +0000863 SpvId raw = this->writeExpression(*arg, out);
John Stiles9aeed132020-11-24 17:36:06 -0500864 if (vectorSize && argType.isScalar()) {
Robert Phillipsc650cc02021-05-14 14:29:23 +0000865 SpvId vector = this->nextId(&arg->type());
866 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
867 this->writeWord(this->getType(argType.toCompound(fContext, vectorSize, 1)), out);
868 this->writeWord(vector, out);
869 for (int i = 0; i < vectorSize; i++) {
870 this->writeWord(raw, out);
871 }
872 result.push_back(vector);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500873 } else {
Robert Phillipsc650cc02021-05-14 14:29:23 +0000874 result.push_back(raw);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500875 }
876 }
877 return result;
878}
879
880void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
881 SpvId signedInst, SpvId unsignedInst,
882 const std::vector<SpvId>& args,
883 OutputStream& out) {
884 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
885 this->writeWord(this->getType(type), out);
886 this->writeWord(id, out);
887 this->writeWord(fGLSLExtendedInstructions, out);
888
889 if (is_float(fContext, type)) {
890 this->writeWord(floatInst, out);
891 } else if (is_signed(fContext, type)) {
892 this->writeWord(signedInst, out);
893 } else if (is_unsigned(fContext, type)) {
894 this->writeWord(unsignedInst, out);
895 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400896 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500897 }
898 for (SpvId a : args) {
899 this->writeWord(a, out);
900 }
901}
902
Greg Daniel64773e62016-11-22 09:44:03 -0500903SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400904 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400905 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400906 const Type& callType = c.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400907 SpvId result = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700908 switch (kind) {
909 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400910 std::vector<SpvId> argumentIds;
911 for (const std::unique_ptr<Expression>& arg : arguments) {
912 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700913 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400914 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400915 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700916 this->writeWord(result, out);
917 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400918 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
919 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700920 this->writeWord(id, out);
921 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400922 break;
923 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400924 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400925 SkASSERT(arguments.size() == 2);
926 SpvId img = this->writeExpression(*arguments[0], out);
927 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400928 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400929 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400930 result,
931 img,
932 sampler,
933 out);
934 break;
935 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400936 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400937 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400938 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400939 args.reserve_back(2);
John Stiles9ce80f72021-03-11 22:35:19 -0500940 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
941 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
John Stiles8cad6372021-04-07 12:31:13 -0400942 ConstructorCompound ctor(/*offset=*/-1, *fContext.fTypes.fInt2, std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400943 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400944 if (arguments.size() == 1) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400945 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400946 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400947 result,
948 img,
949 coords,
950 out);
951 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400952 SkASSERT(arguments.size() == 2);
953 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400954 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400955 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400956 result,
957 img,
958 coords,
959 SpvImageOperandsSampleMask,
960 sample,
961 out);
962 }
963 break;
964 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700965 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500966 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400967 const Type& arg1Type = arguments[1]->type();
968 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500969 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -0500970 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500971 op = SpvOpImageSampleProjImplicitLod;
972 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500973 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500974 }
975 break;
976 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -0500977 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500978 op = SpvOpImageSampleProjImplicitLod;
979 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500980 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500981 }
982 break;
983 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -0500984 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500985 op = SpvOpImageSampleProjImplicitLod;
986 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500987 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500988 }
989 break;
990 case SpvDimCube: // fall through
991 case SpvDimRect: // fall through
992 case SpvDimBuffer: // fall through
993 case SpvDimSubpassData:
994 break;
995 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400996 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400997 SpvId sampler = this->writeExpression(*arguments[0], out);
998 SpvId uv = this->writeExpression(*arguments[1], out);
999 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001000 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -07001001 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001002 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -07001003 out);
1004 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001005 SkASSERT(arguments.size() == 2);
John Stiles270cec22021-02-17 12:59:36 -05001006 if (fProgram.fConfig->fSettings.fSharpenTextures) {
John Stiles9ce80f72021-03-11 22:35:19 -05001007 FloatLiteral lodBias(/*offset=*/-1, /*value=*/-0.5,
1008 fContext.fTypes.fFloat.get());
Brian Osman8a83ca42018-02-12 14:32:17 -05001009 this->writeInstruction(op, type, result, sampler, uv,
1010 SpvImageOperandsBiasMask,
1011 this->writeFloatLiteral(lodBias),
1012 out);
1013 } else {
1014 this->writeInstruction(op, type, result, sampler, uv,
1015 out);
1016 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001017 }
1018 break;
1019 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001020 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001021 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001022 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001023 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001024 SpvOp_ op;
1025 if (is_float(fContext, operandType)) {
1026 op = SpvOpFMod;
1027 } else if (is_signed(fContext, operandType)) {
1028 op = SpvOpSMod;
1029 } else if (is_unsigned(fContext, operandType)) {
1030 op = SpvOpUMod;
1031 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001032 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001033 return 0;
1034 }
1035 this->writeOpCode(op, 5, out);
1036 this->writeWord(this->getType(operandType), out);
1037 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001038 this->writeWord(args[0], out);
1039 this->writeWord(args[1], out);
1040 break;
1041 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001042 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001043 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001044 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001045 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001046 this->writeWord(result, out);
1047 this->writeWord(fn, out);
John Stiles270cec22021-02-17 12:59:36 -05001048 if (fProgram.fConfig->fSettings.fFlipY) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001049 // Flipping Y also negates the Y derivatives.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001050 SpvId flipped = this->nextId(&callType);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001051 this->writeInstruction(SpvOpFNegate, this->getType(callType), flipped, result,
1052 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001053 result = flipped;
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001054 }
1055 break;
1056 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001057 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001058 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001059 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001060 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001061 GLSLstd450UClamp, args, out);
1062 break;
1063 }
1064 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001065 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001066 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001067 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001068 GLSLstd450UMax, args, out);
1069 break;
1070 }
1071 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001072 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001073 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001074 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001075 GLSLstd450UMin, args, out);
1076 break;
1077 }
1078 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001079 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001080 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001081 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001082 SpvOpUndef, args, out);
1083 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001084 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001085 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001086 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001087 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001088 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001089 finalArgs.push_back(arguments[0]->clone());
John Stiles9ce80f72021-03-11 22:35:19 -05001090 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
1091 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001092 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001093 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001094 GLSLstd450UClamp, spvArgs, out);
1095 break;
1096 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001097 case kSmoothStep_SpecialIntrinsic: {
1098 std::vector<SpvId> args = this->vectorize(arguments, out);
1099 SkASSERT(args.size() == 3);
1100 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1101 SpvOpUndef, args, out);
1102 break;
1103 }
1104 case kStep_SpecialIntrinsic: {
1105 std::vector<SpvId> args = this->vectorize(arguments, out);
1106 SkASSERT(args.size() == 2);
1107 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1108 SpvOpUndef, args, out);
1109 break;
1110 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001111 case kMatrixCompMult_SpecialIntrinsic: {
1112 SkASSERT(arguments.size() == 2);
1113 SpvId lhs = this->writeExpression(*arguments[0], out);
1114 SpvId rhs = this->writeExpression(*arguments[1], out);
John Stiles43b593c2021-05-13 22:03:27 -04001115 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
Brian Osmand1b593f2020-12-28 13:00:46 -05001116 break;
1117 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001118 }
1119 return result;
1120}
1121
John Stilesec241542021-02-11 17:50:09 -05001122namespace {
1123struct TempVar {
1124 SpvId spvId;
1125 const Type* type;
1126 std::unique_ptr<SPIRVCodeGenerator::LValue> lvalue;
1127};
1128}
1129
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001130SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001131 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -04001132 if (function.isIntrinsic() && !function.definition()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001133 return this->writeIntrinsicCall(c, out);
1134 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001135 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001136 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001137 if (entry == fFunctionMap.end()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001138 fErrors.error(c.fOffset, "function '" + function.description() + "' is not defined");
1139 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001140 }
John Stilesec241542021-02-11 17:50:09 -05001141 // Temp variables are used to write back out-parameters after the function call is complete.
1142 std::vector<TempVar> tempVars;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001143 std::vector<SpvId> argumentIds;
1144 for (size_t i = 0; i < arguments.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -05001145 // id of temporary variable that we will use to hold this argument, or 0 if it is being
ethannicholasb3058bd2016-07-01 08:22:01 -07001146 // passed directly
1147 SpvId tmpVar;
1148 // if we need a temporary var to store this argument, this is the value to store in the var
1149 SpvId tmpValueId;
Ethan Nicholased84b732020-10-08 11:45:44 -04001150 if (is_out(*function.parameters()[i])) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001151 std::unique_ptr<LValue> lv = this->getLValue(*arguments[i], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001152 SpvId ptr = lv->getPointer();
Ethan Nicholase0707b72021-03-17 11:16:41 -04001153 if (ptr != (SpvId) -1 && lv->isMemoryObjectPointer()) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001154 argumentIds.push_back(ptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001155 continue;
1156 } else {
1157 // lvalue cannot simply be read and written via a pointer (e.g. a swizzle). Need to
1158 // copy it into a temp, call the function, read the value out of the temp, and then
1159 // update the lvalue.
1160 tmpValueId = lv->load(out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001161 tmpVar = this->nextId(nullptr);
John Stilesec241542021-02-11 17:50:09 -05001162 tempVars.push_back(TempVar{tmpVar, &arguments[i]->type(), std::move(lv)});
ethannicholasb3058bd2016-07-01 08:22:01 -07001163 }
1164 } else {
John Stilesec241542021-02-11 17:50:09 -05001165 // See getFunctionType for an explanation of why we're always using pointer parameters.
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001166 tmpValueId = this->writeExpression(*arguments[i], out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001167 tmpVar = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001168 }
Greg Daniel64773e62016-11-22 09:44:03 -05001169 this->writeInstruction(SpvOpVariable,
John Stilesec241542021-02-11 17:50:09 -05001170 this->getPointerType(arguments[i]->type(), SpvStorageClassFunction),
Greg Daniel64773e62016-11-22 09:44:03 -05001171 tmpVar,
ethannicholasb3058bd2016-07-01 08:22:01 -07001172 SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07001173 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001174 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001175 argumentIds.push_back(tmpVar);
ethannicholasb3058bd2016-07-01 08:22:01 -07001176 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001177 SpvId result = this->nextId(nullptr);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001178 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001179 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001180 this->writeWord(result, out);
1181 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001182 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001183 this->writeWord(id, out);
1184 }
John Stilesec241542021-02-11 17:50:09 -05001185 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
1186 for (const TempVar& tempVar : tempVars) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001187 SpvId load = this->nextId(tempVar.type);
John Stilesec241542021-02-11 17:50:09 -05001188 this->writeInstruction(SpvOpLoad, getType(*tempVar.type), load, tempVar.spvId, out);
John Stilesec241542021-02-11 17:50:09 -05001189 tempVar.lvalue->store(load, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001190 }
1191 return result;
1192}
1193
John Stiles2938eea2021-04-01 18:58:25 -04001194SpvId SPIRVCodeGenerator::writeConstantVector(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001195 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001196 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001197
John Stiles9cfaa4f2021-01-06 17:52:00 -05001198 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001199 SPIRVVectorConstant key{this->getType(type),
1200 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001201
John Stiles21a50ec2021-04-06 14:49:36 -04001202 for (int n = 0; n < type.columns(); n++) {
1203 const Expression* expr = c.getConstantSubexpression(n);
1204 if (!expr) {
1205 SkDEBUGFAILF("writeConstantVector: %s not actually constant", c.description().c_str());
1206 return (SpvId)-1;
John Stiles9cfaa4f2021-01-06 17:52:00 -05001207 }
John Stiles21a50ec2021-04-06 14:49:36 -04001208 key.fValueId[n] = this->writeExpression(*expr, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001209 }
John Stilescd806892021-01-06 13:33:31 -05001210
1211 // Check to see if we've already synthesized this vector constant.
1212 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1213 if (newlyCreated) {
1214 // Emit an OpConstantComposite instruction for this constant.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001215 SpvId result = this->nextId(&type);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001216 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001217 this->writeWord(key.fTypeId, fConstantBuffer);
1218 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001219 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001220 this->writeWord(key.fValueId[i], fConstantBuffer);
1221 }
1222 iter->second = result;
1223 }
1224 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001225}
1226
John Stilesb14a8192021-04-05 11:40:46 -04001227SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
1228 const Type& inputType,
1229 const Type& outputType,
1230 OutputStream& out) {
1231 if (outputType.isFloat()) {
1232 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
1233 }
1234 if (outputType.isSigned()) {
1235 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
1236 }
1237 if (outputType.isUnsigned()) {
1238 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
1239 }
1240 if (outputType.isBoolean()) {
1241 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
1242 }
1243
1244 fErrors.error(-1, "unsupported cast: " + inputType.description() +
1245 " to " + outputType.description());
1246 return inputExprId;
1247}
1248
John Stilesfd7252f2021-04-04 22:24:40 -04001249SpvId SPIRVCodeGenerator::writeFloatConstructor(const AnyConstructor& c, OutputStream& out) {
1250 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001251 SkASSERT(c.type().isFloat());
John Stilesfd7252f2021-04-04 22:24:40 -04001252 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001253 SpvId expressionId = this->writeExpression(ctorExpr, out);
1254 return this->castScalarToFloat(expressionId, ctorExpr.type(), c.type(), out);
1255}
1256
1257SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
1258 const Type& outputType, OutputStream& out) {
1259 // Casting a float to float is a no-op.
1260 if (inputType.isFloat()) {
1261 return inputId;
1262 }
1263
1264 // Given the input type, generate the appropriate instruction to cast to float.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001265 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001266 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001267 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
John Stiles9ce80f72021-03-11 22:35:19 -05001268 FloatLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001269 SpvId oneID = this->writeFloatLiteral(one);
John Stiles9ce80f72021-03-11 22:35:19 -05001270 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001271 SpvId zeroID = this->writeFloatLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001272 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1273 inputId, oneID, zeroID, out);
1274 } else if (inputType.isSigned()) {
1275 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
1276 } else if (inputType.isUnsigned()) {
1277 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001278 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001279 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
1280 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001281 }
1282 return result;
1283}
1284
John Stilesfd7252f2021-04-04 22:24:40 -04001285SpvId SPIRVCodeGenerator::writeIntConstructor(const AnyConstructor& c, OutputStream& out) {
1286 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001287 SkASSERT(c.type().isSigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001288 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001289 SpvId expressionId = this->writeExpression(ctorExpr, out);
1290 return this->castScalarToSignedInt(expressionId, ctorExpr.type(), c.type(), out);
1291}
1292
1293SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
1294 const Type& outputType, OutputStream& out) {
1295 // Casting a signed int to signed int is a no-op.
1296 if (inputType.isSigned()) {
1297 return inputId;
1298 }
1299
1300 // Given the input type, generate the appropriate instruction to cast to signed int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001301 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001302 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001303 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
John Stiles54e7c052021-01-11 14:22:36 -05001304 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001305 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001306 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001307 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001308 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1309 inputId, oneID, zeroID, out);
1310 } else if (inputType.isFloat()) {
1311 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
1312 } else if (inputType.isUnsigned()) {
1313 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
1314 } else {
1315 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
1316 inputType.description().c_str());
1317 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001318 }
1319 return result;
1320}
1321
John Stilesfd7252f2021-04-04 22:24:40 -04001322SpvId SPIRVCodeGenerator::writeUIntConstructor(const AnyConstructor& c, OutputStream& out) {
1323 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001324 SkASSERT(c.type().isUnsigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001325 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001326 SpvId expressionId = this->writeExpression(ctorExpr, out);
1327 return this->castScalarToUnsignedInt(expressionId, ctorExpr.type(), c.type(), out);
1328}
1329
1330SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
1331 const Type& outputType, OutputStream& out) {
1332 // Casting an unsigned int to unsigned int is a no-op.
1333 if (inputType.isUnsigned()) {
1334 return inputId;
1335 }
1336
John Stiles48c28842021-01-14 11:05:03 -05001337 // Given the input type, generate the appropriate instruction to cast to unsigned int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001338 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001339 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001340 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
John Stiles54e7c052021-01-11 14:22:36 -05001341 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001342 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001343 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001344 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001345 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1346 inputId, oneID, zeroID, out);
1347 } else if (inputType.isFloat()) {
1348 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
1349 } else if (inputType.isSigned()) {
1350 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001351 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001352 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
1353 inputType.description().c_str());
1354 return (SpvId)-1;
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001355 }
1356 return result;
1357}
1358
John Stilesfd7252f2021-04-04 22:24:40 -04001359SpvId SPIRVCodeGenerator::writeBooleanConstructor(const AnyConstructor& c, OutputStream& out) {
1360 SkASSERT(c.argumentSpan().size() == 1);
John Stilesa60fb172021-01-14 11:06:20 -05001361 SkASSERT(c.type().isBoolean());
John Stilesfd7252f2021-04-04 22:24:40 -04001362 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesa60fb172021-01-14 11:06:20 -05001363 SpvId expressionId = this->writeExpression(ctorExpr, out);
1364 return this->castScalarToBoolean(expressionId, ctorExpr.type(), c.type(), out);
1365}
1366
John Stiles48c28842021-01-14 11:05:03 -05001367SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
1368 const Type& outputType, OutputStream& out) {
1369 // Casting a bool to bool is a no-op.
1370 if (inputType.isBoolean()) {
1371 return inputId;
1372 }
1373
1374 // Given the input type, generate the appropriate instruction to cast to bool.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001375 SpvId result = this->nextId(nullptr);
John Stiles48c28842021-01-14 11:05:03 -05001376 if (inputType.isSigned()) {
1377 // Synthesize a boolean result by comparing the input against a signed zero literal.
1378 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
1379 SpvId zeroID = this->writeIntLiteral(zero);
1380 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1381 inputId, zeroID, out);
1382 } else if (inputType.isUnsigned()) {
1383 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
1384 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
1385 SpvId zeroID = this->writeIntLiteral(zero);
1386 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1387 inputId, zeroID, out);
1388 } else if (inputType.isFloat()) {
1389 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
1390 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
1391 SpvId zeroID = this->writeFloatLiteral(zero);
1392 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
1393 inputId, zeroID, out);
1394 } else {
1395 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
1396 return (SpvId)-1;
1397 }
1398 return result;
1399}
1400
Ethan Nicholas84645e32017-02-09 13:57:14 -05001401void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001402 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05001403 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001404 SpvId zeroId = this->writeFloatLiteral(zero);
1405 std::vector<SpvId> columnIds;
John Stiles392d8292021-04-09 12:14:03 -04001406 columnIds.reserve(type.columns());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001407 for (int column = 0; column < type.columns(); column++) {
1408 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1409 out);
John Stiles392d8292021-04-09 12:14:03 -04001410 this->writeWord(this->getType(type.componentType().toCompound(
1411 fContext, /*columns=*/type.rows(), /*rows=*/1)),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001412 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001413 SpvId columnId = this->nextId(&type);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001414 this->writeWord(columnId, out);
1415 columnIds.push_back(columnId);
John Stiles392d8292021-04-09 12:14:03 -04001416 for (int row = 0; row < type.rows(); row++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001417 this->writeWord(row == column ? diagonal : zeroId, out);
1418 }
1419 }
1420 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1421 out);
1422 this->writeWord(this->getType(type), out);
1423 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001424 for (SpvId columnId : columnIds) {
1425 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001426 }
1427}
1428
John Stiles268a73f2021-04-07 12:30:22 -04001429SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
1430 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001431 SkASSERT(srcType.isMatrix());
1432 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001433 SkASSERT(srcType.componentType() == dstType.componentType());
John Stiles268a73f2021-04-07 12:30:22 -04001434 SpvId id = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001435 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1436 srcType.rows(),
1437 1));
1438 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1439 dstType.rows(),
1440 1));
John Stiles92671832021-04-06 09:24:55 -04001441 SkASSERT(dstType.componentType().isFloat());
1442 FloatLiteral zero(/*offset=*/-1, /*value=*/0.0, &dstType.componentType());
1443 const SpvId zeroId = this->writeFloatLiteral(zero);
1444 FloatLiteral one(/*offset=*/-1, /*value=*/1.0, &dstType.componentType());
1445 const SpvId oneId = this->writeFloatLiteral(one);
1446
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001447 SpvId columns[4];
1448 for (int i = 0; i < dstType.columns(); i++) {
1449 if (i < srcType.columns()) {
1450 // we're still inside the src matrix, copy the column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001451 SpvId srcColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001452 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1453 SpvId dstColumn;
1454 if (srcType.rows() == dstType.rows()) {
1455 // columns are equal size, don't need to do anything
1456 dstColumn = srcColumn;
1457 }
1458 else if (dstType.rows() > srcType.rows()) {
1459 // dst column is bigger, need to zero-pad it
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001460 dstColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001461 int delta = dstType.rows() - srcType.rows();
1462 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1463 this->writeWord(dstColumnType, out);
1464 this->writeWord(dstColumn, out);
1465 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001466 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
1467 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001468 }
1469 }
1470 else {
1471 // dst column is smaller, need to swizzle the src column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001472 dstColumn = this->nextId(&dstType);
John Stiles92671832021-04-06 09:24:55 -04001473 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001474 this->writeWord(dstColumnType, out);
1475 this->writeWord(dstColumn, out);
1476 this->writeWord(srcColumn, out);
1477 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001478 for (int j = 0; j < dstType.rows(); j++) {
John Stilesf621e232020-08-25 13:33:02 -04001479 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001480 }
1481 }
1482 columns[i] = dstColumn;
1483 } else {
John Stiles92671832021-04-06 09:24:55 -04001484 // we're past the end of the src matrix, need to synthesize an identity-matrix column
1485 SpvId identityColumn = this->nextId(&dstType);
1486 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1487 this->writeWord(dstColumnType, out);
1488 this->writeWord(identityColumn, out);
1489 for (int j = 0; j < dstType.rows(); ++j) {
1490 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001491 }
John Stiles92671832021-04-06 09:24:55 -04001492 columns[i] = identityColumn;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001493 }
1494 }
1495 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1496 this->writeWord(this->getType(dstType), out);
1497 this->writeWord(id, out);
1498 for (int i = 0; i < dstType.columns(); i++) {
1499 this->writeWord(columns[i], out);
1500 }
John Stiles268a73f2021-04-07 12:30:22 -04001501 return id;
Ethan Nicholas84645e32017-02-09 13:57:14 -05001502}
1503
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001504void SPIRVCodeGenerator::addColumnEntry(SpvId columnType, Precision precision,
1505 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001506 std::vector<SpvId>* columnIds,
1507 int* currentCount, int rows, SpvId entry,
1508 OutputStream& out) {
1509 SkASSERT(*currentCount < rows);
1510 ++(*currentCount);
1511 currentColumn->push_back(entry);
1512 if (*currentCount == rows) {
1513 *currentCount = 0;
1514 this->writeOpCode(SpvOpCompositeConstruct, 3 + currentColumn->size(), out);
1515 this->writeWord(columnType, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001516 SpvId columnId = this->nextId(precision);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001517 this->writeWord(columnId, out);
1518 columnIds->push_back(columnId);
1519 for (SpvId id : *currentColumn) {
1520 this->writeWord(id, out);
1521 }
1522 currentColumn->clear();
1523 }
1524}
1525
John Stiles8cad6372021-04-07 12:31:13 -04001526SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001527 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001528 SkASSERT(type.isMatrix());
John Stiles2bec8ab2021-04-06 18:40:04 -04001529 SkASSERT(!c.arguments().empty());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001530 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001531 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1532 // an instruction
1533 std::vector<SpvId> arguments;
John Stiles2bec8ab2021-04-06 18:40:04 -04001534 arguments.reserve(c.arguments().size());
1535 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1536 arguments.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001537 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001538 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001539 int rows = type.rows();
1540 int columns = type.columns();
John Stiles268a73f2021-04-07 12:30:22 -04001541 if (arguments.size() == 1 && arg0Type.isVector()) {
1542 // Special-case handling of float4 -> mat2x2.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001543 SkASSERT(type.rows() == 2 && type.columns() == 2);
1544 SkASSERT(arg0Type.columns() == 4);
1545 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001546 SpvId v[4];
1547 for (int i = 0; i < 4; ++i) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001548 v[i] = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001549 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1550 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001551 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001552 SpvId columnType = this->getType(type.componentType().toCompound(fContext, 2, 1));
Ethan Nicholas7f015882021-03-23 14:16:52 -04001553 SpvId column1 = this->nextId(&type);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001554 this->writeInstruction(SpvOpCompositeConstruct, columnType, column1, v[0], v[1], out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04001555 SpvId column2 = this->nextId(&type);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001556 this->writeInstruction(SpvOpCompositeConstruct, columnType, column2, v[2], v[3], out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001557 this->writeInstruction(SpvOpCompositeConstruct, this->getType(type), result, column1,
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001558 column2, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001559 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001560 SpvId columnType = this->getType(type.componentType().toCompound(fContext, rows, 1));
ethannicholasb3058bd2016-07-01 08:22:01 -07001561 std::vector<SpvId> columnIds;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001562 // ids of vectors and scalars we have written to the current column so far
1563 std::vector<SpvId> currentColumn;
1564 // the total number of scalars represented by currentColumn's entries
ethannicholasb3058bd2016-07-01 08:22:01 -07001565 int currentCount = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001566 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
ethannicholasb3058bd2016-07-01 08:22:01 -07001567 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001568 const Type& argType = c.arguments()[i]->type();
John Stiles9aeed132020-11-24 17:36:06 -05001569 if (currentCount == 0 && argType.isVector() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001570 argType.columns() == type.rows()) {
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001571 // this is a complete column by itself
ethannicholasb3058bd2016-07-01 08:22:01 -07001572 columnIds.push_back(arguments[i]);
ethannicholasb3058bd2016-07-01 08:22:01 -07001573 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001574 if (argType.columns() == 1) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001575 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1576 &currentCount, rows, arguments[i], out);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001577 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001578 SpvId componentType = this->getType(argType.componentType());
1579 for (int j = 0; j < argType.columns(); ++j) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001580 SpvId swizzle = this->nextId(&argType);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001581 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1582 arguments[i], j, out);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001583 this->addColumnEntry(columnType, precision, &currentColumn, &columnIds,
1584 &currentCount, rows, swizzle, out);
Ethan Nicholasbe850ad2018-04-27 10:36:31 -04001585 }
1586 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001587 }
1588 }
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001589 SkASSERT(columnIds.size() == (size_t) columns);
ethannicholasb3058bd2016-07-01 08:22:01 -07001590 this->writeOpCode(SpvOpCompositeConstruct, 3 + columns, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001591 this->writeWord(this->getType(type), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001592 this->writeWord(result, out);
1593 for (SpvId id : columnIds) {
1594 this->writeWord(id, out);
1595 }
1596 }
1597 return result;
1598}
1599
John Stiles8cad6372021-04-07 12:31:13 -04001600SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1601 OutputStream& out) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001602 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
1603 : this->writeVectorConstructor(c, out);
1604}
1605
John Stiles8cad6372021-04-07 12:31:13 -04001606SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001607 const Type& type = c.type();
John Stilesd986f472021-04-06 15:54:43 -04001608 const Type& componentType = type.componentType();
John Stiles9aeed132020-11-24 17:36:06 -05001609 SkASSERT(type.isVector());
John Stilesd986f472021-04-06 15:54:43 -04001610
1611 if (c.isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001612 return this->writeConstantVector(c);
1613 }
John Stilesd986f472021-04-06 15:54:43 -04001614
ethannicholasb3058bd2016-07-01 08:22:01 -07001615 std::vector<SpvId> arguments;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001616 for (size_t i = 0; i < c.arguments().size(); i++) {
1617 const Type& argType = c.arguments()[i]->type();
John Stilesd986f472021-04-06 15:54:43 -04001618 SkASSERT(componentType == argType.componentType());
John Stiles48c28842021-01-14 11:05:03 -05001619
John Stilesd986f472021-04-06 15:54:43 -04001620 if (argType.isVector()) {
1621 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
1622 // vector arguments at all, so we always extract each vector component and pass them
1623 // into OpCompositeConstruct individually.
1624 SpvId vec = this->writeExpression(*c.arguments()[i], out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001625 for (int j = 0; j < argType.columns(); j++) {
John Stilesd986f472021-04-06 15:54:43 -04001626 SpvId componentId = this->nextId(&componentType);
1627 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
1628 componentId, vec, j, out);
1629 arguments.push_back(componentId);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001630 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001631 } else {
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001632 arguments.push_back(this->writeExpression(*c.arguments()[i], out));
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001633 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001634 }
John Stilesb14a8192021-04-05 11:40:46 -04001635
1636 return this->writeComposite(arguments, type, out);
1637}
1638
1639SpvId SPIRVCodeGenerator::writeComposite(const std::vector<SpvId>& arguments,
1640 const Type& type,
1641 OutputStream& out) {
John Stilesd47330f2021-04-08 23:25:52 -04001642 SkASSERT(arguments.size() == (type.isStruct() ? type.fields().size() : (size_t)type.columns()));
John Stiles2938eea2021-04-01 18:58:25 -04001643
Ethan Nicholas7f015882021-03-23 14:16:52 -04001644 SpvId result = this->nextId(&type);
John Stiles2938eea2021-04-01 18:58:25 -04001645 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1646 this->writeWord(this->getType(type), out);
1647 this->writeWord(result, out);
1648 for (SpvId id : arguments) {
1649 this->writeWord(id, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001650 }
1651 return result;
1652}
1653
John Stiles2938eea2021-04-01 18:58:25 -04001654SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, OutputStream& out) {
1655 // Use writeConstantVector to deduplicate constant splats.
1656 if (c.isCompileTimeConstant()) {
1657 return this->writeConstantVector(c);
1658 }
1659
1660 // Write the splat argument.
1661 SpvId argument = this->writeExpression(*c.argument(), out);
1662
1663 // Generate a OpCompositeConstruct which repeats the argument N times.
John Stilesb14a8192021-04-05 11:40:46 -04001664 std::vector<SpvId> arguments(/*count*/ c.type().columns(), /*value*/ argument);
1665 return this->writeComposite(arguments, c.type(), out);
John Stiles2938eea2021-04-01 18:58:25 -04001666}
1667
1668
John Stilesd47330f2021-04-08 23:25:52 -04001669SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, OutputStream& out) {
1670 SkASSERT(c.type().isArray() || c.type().isStruct());
1671 auto ctorArgs = c.argumentSpan();
1672
Ethan Nicholasbd553222017-07-18 15:54:59 -04001673 std::vector<SpvId> arguments;
John Stilesd47330f2021-04-08 23:25:52 -04001674 arguments.reserve(ctorArgs.size());
1675 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
1676 arguments.push_back(this->writeExpression(*arg, out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001677 }
John Stilesd47330f2021-04-08 23:25:52 -04001678
1679 return this->writeComposite(arguments, c.type(), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001680}
1681
John Stilesfd7252f2021-04-04 22:24:40 -04001682SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1683 OutputStream& out) {
1684 const Type& type = c.type();
1685 if (this->getActualType(type) == this->getActualType(c.argument()->type())) {
1686 return this->writeExpression(*c.argument(), out);
1687 }
John Stilesb14a8192021-04-05 11:40:46 -04001688
1689 const Expression& ctorExpr = *c.argument();
1690 SpvId expressionId = this->writeExpression(ctorExpr, out);
1691 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
1692}
1693
John Stiles8cad6372021-04-07 12:31:13 -04001694SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
1695 OutputStream& out) {
John Stilesb14a8192021-04-05 11:40:46 -04001696 const Type& ctorType = c.type();
1697 const Type& argType = c.argument()->type();
John Stiles268a73f2021-04-07 12:30:22 -04001698 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
John Stilesb14a8192021-04-05 11:40:46 -04001699
John Stiles268a73f2021-04-07 12:30:22 -04001700 // Write the composite that we are casting. If the actual type matches, we are done.
1701 SpvId compositeId = this->writeExpression(*c.argument(), out);
John Stilesb14a8192021-04-05 11:40:46 -04001702 if (this->getActualType(ctorType) == this->getActualType(argType)) {
John Stiles268a73f2021-04-07 12:30:22 -04001703 return compositeId;
1704 }
1705
1706 // writeMatrixCopy can cast matrices to a different type.
1707 if (ctorType.isMatrix()) {
1708 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
John Stilesfd7252f2021-04-04 22:24:40 -04001709 }
John Stilesb14a8192021-04-05 11:40:46 -04001710
1711 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
John Stilesd986f472021-04-06 15:54:43 -04001712 // components and convert each one manually.
John Stilesb14a8192021-04-05 11:40:46 -04001713 const Type& srcType = argType.componentType();
1714 const Type& dstType = ctorType.componentType();
1715
1716 std::vector<SpvId> arguments;
John Stiles268a73f2021-04-07 12:30:22 -04001717 arguments.reserve(argType.columns());
John Stilesb14a8192021-04-05 11:40:46 -04001718 for (int index = 0; index < argType.columns(); ++index) {
1719 SpvId componentId = this->nextId(&srcType);
1720 this->writeInstruction(SpvOpCompositeExtract, this->getType(srcType), componentId,
John Stiles268a73f2021-04-07 12:30:22 -04001721 compositeId, index, out);
John Stilesb14a8192021-04-05 11:40:46 -04001722 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
John Stilesfd7252f2021-04-04 22:24:40 -04001723 }
John Stilesb14a8192021-04-05 11:40:46 -04001724
1725 return this->writeComposite(arguments, ctorType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001726}
1727
John Stilese1182782021-03-30 22:09:37 -04001728SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
1729 OutputStream& out) {
1730 const Type& type = c.type();
1731 SkASSERT(type.isMatrix());
1732 SkASSERT(c.argument()->type().isScalar());
1733
1734 // Write out the scalar argument.
1735 SpvId argument = this->writeExpression(*c.argument(), out);
1736
1737 // Build the diagonal matrix.
1738 SpvId result = this->nextId(&type);
1739 this->writeUniformScaleMatrix(result, argument, type, out);
1740 return result;
1741}
1742
John Stiles5abb9e12021-04-06 13:47:19 -04001743SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1744 OutputStream& out) {
1745 // Write the input matrix.
1746 SpvId argument = this->writeExpression(*c.argument(), out);
1747
1748 // Use matrix-copy to resize the input matrix to its new size.
John Stiles268a73f2021-04-07 12:30:22 -04001749 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
John Stiles5abb9e12021-04-06 13:47:19 -04001750}
1751
John Stiles9485b552021-01-27 11:47:00 -05001752static SpvStorageClass_ get_storage_class(const Variable& var,
1753 SpvStorageClass_ fallbackStorageClass) {
1754 const Modifiers& modifiers = var.modifiers();
ethannicholasb3058bd2016-07-01 08:22:01 -07001755 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001756 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001757 return SpvStorageClassInput;
John Stiles9485b552021-01-27 11:47:00 -05001758 }
1759 if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001760 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001761 return SpvStorageClassOutput;
John Stiles9485b552021-01-27 11:47:00 -05001762 }
1763 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001764 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001765 return SpvStorageClassPushConstant;
1766 }
John Stiles9485b552021-01-27 11:47:00 -05001767 if (var.type().typeKind() == Type::TypeKind::kSampler ||
1768 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
1769 var.type().typeKind() == Type::TypeKind::kTexture) {
1770 return SpvStorageClassUniformConstant;
1771 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001772 return SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07001773 }
John Stiles9485b552021-01-27 11:47:00 -05001774 return fallbackStorageClass;
ethannicholasb3058bd2016-07-01 08:22:01 -07001775}
1776
John Stiles9485b552021-01-27 11:47:00 -05001777static SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001778 switch (expr.kind()) {
1779 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001780 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001781 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001782 return SpvStorageClassFunction;
1783 }
John Stiles9485b552021-01-27 11:47:00 -05001784 return get_storage_class(var, SpvStorageClassPrivate);
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001785 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001786 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001787 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001788 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001789 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001790 default:
1791 return SpvStorageClassFunction;
1792 }
1793}
1794
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001795std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001796 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001797 switch (expr.kind()) {
1798 case Expression::Kind::kIndex: {
John Stiles0693fb82021-01-22 18:27:52 -05001799 const IndexExpression& indexExpr = expr.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001800 chain = this->getAccessChain(*indexExpr.base(), out);
1801 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001802 break;
1803 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001804 case Expression::Kind::kFieldAccess: {
John Stiles0693fb82021-01-22 18:27:52 -05001805 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001806 chain = this->getAccessChain(*fieldExpr.base(), out);
John Stiles9ce80f72021-03-11 22:35:19 -05001807 IntLiteral index(/*offset=*/-1, fieldExpr.fieldIndex(), fContext.fTypes.fInt.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07001808 chain.push_back(this->writeIntLiteral(index));
1809 break;
1810 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001811 default: {
1812 SpvId id = this->getLValue(expr, out)->getPointer();
John Stiles3f14d282021-02-05 09:31:04 -05001813 SkASSERT(id != (SpvId) -1);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001814 chain.push_back(id);
1815 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001816 }
1817 return chain;
1818}
1819
1820class PointerLValue : public SPIRVCodeGenerator::LValue {
1821public:
Ethan Nicholase0707b72021-03-17 11:16:41 -04001822 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001823 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001824 : fGen(gen)
1825 , fPointer(pointer)
Ethan Nicholase0707b72021-03-17 11:16:41 -04001826 , fIsMemoryObject(isMemoryObject)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001827 , fType(type)
1828 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001829
John Stiles1cf2c8d2020-08-13 22:58:04 -04001830 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001831 return fPointer;
1832 }
1833
Ethan Nicholase0707b72021-03-17 11:16:41 -04001834 bool isMemoryObjectPointer() const override {
1835 return fIsMemoryObject;
1836 }
1837
John Stiles1cf2c8d2020-08-13 22:58:04 -04001838 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001839 SpvId result = fGen.nextId(fPrecision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001840 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1841 return result;
1842 }
1843
John Stiles1cf2c8d2020-08-13 22:58:04 -04001844 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001845 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1846 }
1847
1848private:
1849 SPIRVCodeGenerator& fGen;
1850 const SpvId fPointer;
Ethan Nicholase0707b72021-03-17 11:16:41 -04001851 const bool fIsMemoryObject;
ethannicholasb3058bd2016-07-01 08:22:01 -07001852 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001853 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001854};
1855
1856class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1857public:
John Stiles750109b2020-10-30 13:45:46 -04001858 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001859 const Type& baseType, const Type& swizzleType)
ethannicholasb3058bd2016-07-01 08:22:01 -07001860 : fGen(gen)
1861 , fVecPointer(vecPointer)
1862 , fComponents(components)
John Stiles3f14d282021-02-05 09:31:04 -05001863 , fBaseType(&baseType)
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001864 , fSwizzleType(&swizzleType) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001865
John Stiles3f14d282021-02-05 09:31:04 -05001866 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
1867 ComponentArray updatedSwizzle;
1868 for (int8_t component : components) {
1869 if (component < 0 || component >= fComponents.count()) {
1870 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
1871 return false;
1872 }
1873 updatedSwizzle.push_back(fComponents[component]);
1874 }
1875 fComponents = updatedSwizzle;
1876 fSwizzleType = &newType;
1877 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001878 }
1879
John Stiles1cf2c8d2020-08-13 22:58:04 -04001880 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001881 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001882 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001883 SpvId result = fGen.nextId(fBaseType);
ethannicholasb3058bd2016-07-01 08:22:01 -07001884 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
John Stiles3f14d282021-02-05 09:31:04 -05001885 fGen.writeWord(fGen.getType(*fSwizzleType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001886 fGen.writeWord(result, out);
1887 fGen.writeWord(base, out);
1888 fGen.writeWord(base, out);
1889 for (int component : fComponents) {
1890 fGen.writeWord(component, out);
1891 }
1892 return result;
1893 }
1894
John Stiles1cf2c8d2020-08-13 22:58:04 -04001895 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001896 // use OpVectorShuffle to mix and match the vector components. We effectively create
1897 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001898 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001899 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001900 // float3L = ...;
1901 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001902 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001903 // 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 -07001904 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1905 // (3, 1, 4).
Ethan Nicholas7f015882021-03-23 14:16:52 -04001906 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001907 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001908 SpvId shuffle = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001909 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
1910 fGen.writeWord(fGen.getType(*fBaseType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001911 fGen.writeWord(shuffle, out);
1912 fGen.writeWord(base, out);
1913 fGen.writeWord(value, out);
John Stiles3f14d282021-02-05 09:31:04 -05001914 for (int i = 0; i < fBaseType->columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001915 // current offset into the virtual vector, defaults to pulling the unmodified
1916 // value from the left side
1917 int offset = i;
1918 // check to see if we are writing this component
1919 for (size_t j = 0; j < fComponents.size(); j++) {
1920 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001921 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001922 // the correct component of the right side instead of preserving the
1923 // value from the left
John Stiles3f14d282021-02-05 09:31:04 -05001924 offset = (int) (j + fBaseType->columns());
ethannicholasb3058bd2016-07-01 08:22:01 -07001925 break;
1926 }
1927 }
1928 fGen.writeWord(offset, out);
1929 }
1930 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1931 }
1932
1933private:
1934 SPIRVCodeGenerator& fGen;
1935 const SpvId fVecPointer;
John Stiles3f14d282021-02-05 09:31:04 -05001936 ComponentArray fComponents;
1937 const Type* fBaseType;
1938 const Type* fSwizzleType;
ethannicholasb3058bd2016-07-01 08:22:01 -07001939};
1940
John Stilese40d1662021-01-29 10:08:50 -05001941int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
1942 auto iter = fTopLevelUniformMap.find(&var);
1943 return (iter != fTopLevelUniformMap.end()) ? iter->second : -1;
1944}
1945
Greg Daniel64773e62016-11-22 09:44:03 -05001946std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001947 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001948 const Type& type = expr.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001949 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
Ethan Nicholase6592142020-09-08 10:22:09 -04001950 switch (expr.kind()) {
1951 case Expression::Kind::kVariableReference: {
John Stiles0de76f72021-01-29 09:19:39 -05001952 const Variable& var = *expr.as<VariableReference>().variable();
John Stilese40d1662021-01-29 10:08:50 -05001953 int uniformIdx = this->findUniformFieldIndex(var);
1954 if (uniformIdx >= 0) {
John Stiles9ce80f72021-03-11 22:35:19 -05001955 IntLiteral uniformIdxLiteral{/*offset=*/-1, uniformIdx, fContext.fTypes.fInt.get()};
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001956 SpvId memberId = this->nextId(nullptr);
John Stilese40d1662021-01-29 10:08:50 -05001957 SpvId typeId = this->getPointerType(type, SpvStorageClassUniform);
1958 SpvId uniformIdxId = this->writeIntLiteral(uniformIdxLiteral);
1959 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
1960 uniformIdxId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04001961 return std::make_unique<PointerLValue>(*this, memberId,
1962 /*isMemoryObjectPointer=*/true,
1963 this->getType(type), precision);
John Stilese40d1662021-01-29 10:08:50 -05001964 }
1965 SpvId typeId;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001966 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
John Stilesad2d4942020-12-11 16:55:58 -05001967 typeId = this->getType(*Type::MakeArrayType("sk_in", var.type().componentType(),
1968 fSkInCount));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001969 } else {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05001970 typeId = this->getType(type, this->memoryLayoutForVariable(var));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001971 }
ethannicholasd598f792016-07-25 10:08:54 -07001972 auto entry = fVariableMap.find(&var);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001973 SkASSERT(entry != fVariableMap.end());
Ethan Nicholase0707b72021-03-17 11:16:41 -04001974 return std::make_unique<PointerLValue>(*this, entry->second,
1975 /*isMemoryObjectPointer=*/true,
1976 typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001977 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001978 case Expression::Kind::kIndex: // fall through
1979 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001980 std::vector<SpvId> chain = this->getAccessChain(expr, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001981 SpvId member = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001982 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001983 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001984 this->writeWord(member, out);
1985 for (SpvId idx : chain) {
1986 this->writeWord(idx, out);
1987 }
Ethan Nicholase0707b72021-03-17 11:16:41 -04001988 return std::make_unique<PointerLValue>(*this, member, /*isMemoryObjectPointer=*/false,
1989 this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001990 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001991 case Expression::Kind::kSwizzle: {
John Stiles0693fb82021-01-22 18:27:52 -05001992 const Swizzle& swizzle = expr.as<Swizzle>();
John Stiles3f14d282021-02-05 09:31:04 -05001993 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
1994 if (lvalue->applySwizzle(swizzle.components(), type)) {
1995 return lvalue;
1996 }
1997 SpvId base = lvalue->getPointer();
1998 if (base == (SpvId) -1) {
John Stiles5570c512020-11-19 17:58:07 -05001999 fErrors.error(swizzle.fOffset, "unable to retrieve lvalue from swizzle");
2000 }
John Stiles3f14d282021-02-05 09:31:04 -05002001 if (swizzle.components().size() == 1) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002002 SpvId member = this->nextId(nullptr);
John Stilesb5db4822021-01-21 13:04:40 -05002003 SpvId typeId = this->getPointerType(type, get_storage_class(*swizzle.base()));
John Stiles9ce80f72021-03-11 22:35:19 -05002004 IntLiteral index(/*offset=*/-1, swizzle.components()[0],
2005 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -05002006 SpvId indexId = this->writeIntLiteral(index);
2007 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002008 return std::make_unique<PointerLValue>(*this,
2009 member,
2010 /*isMemoryObjectPointer=*/false,
2011 this->getType(type),
John Stiles5570c512020-11-19 17:58:07 -05002012 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002013 } else {
John Stiles5570c512020-11-19 17:58:07 -05002014 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002015 swizzle.base()->type(), type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002016 }
2017 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002018 default: {
ethannicholasb3058bd2016-07-01 08:22:01 -07002019 // expr isn't actually an lvalue, create a dummy variable for it. This case happens due
Greg Daniel64773e62016-11-22 09:44:03 -05002020 // to the need to store values in temporary variables during function calls (see
ethannicholasb3058bd2016-07-01 08:22:01 -07002021 // comments in getFunctionType); erroneous uses of rvalues as lvalues should have been
2022 // caught by IRGenerator
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002023 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002024 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
2025 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07002026 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002027 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002028 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
2029 this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002030 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002031 }
2032}
2033
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002034SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
John Stiles1e1fe122021-01-29 12:18:46 -05002035 SpvId result = this->getLValue(ref, out)->load(out);
John Stilese40d1662021-01-29 10:08:50 -05002036
John Stiles1e1fe122021-01-29 12:18:46 -05002037 // Handle the "flipY" setting when reading sk_FragCoord.
2038 const Variable* variable = ref.variable();
John Stilese40d1662021-01-29 10:08:50 -05002039 if (variable->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN &&
John Stiles270cec22021-02-17 12:59:36 -05002040 fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002041 // The x component never changes, so just grab it
Ethan Nicholas7f015882021-03-23 14:16:52 -04002042 SpvId xId = this->nextId(Precision::kDefault);
John Stiles54e7c052021-01-11 14:22:36 -05002043 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat), xId,
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002044 result, 0, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002045
2046 // Calculate the y component which may need to be flipped
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002047 SpvId rawYId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002048 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat),
2049 rawYId, result, 1, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002050 SpvId flippedYId = 0;
John Stiles270cec22021-02-17 12:59:36 -05002051 if (fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002052 // need to remap to a top-left coordinate system
2053 if (fRTHeightStructId == (SpvId)-1) {
2054 // height variable hasn't been written yet
Greg Daniela85e4bf2020-06-17 16:32:45 -04002055 SkASSERT(fRTHeightFieldIndex == (SpvId)-1);
2056 std::vector<Type::Field> fields;
John Stiles270cec22021-02-17 12:59:36 -05002057 if (fProgram.fConfig->fSettings.fRTHeightOffset < 0) {
John Stiles5570c512020-11-19 17:58:07 -05002058 fErrors.error(ref.fOffset, "RTHeightOffset is negative");
2059 }
Greg Daniela85e4bf2020-06-17 16:32:45 -04002060 fields.emplace_back(
John Stilese40d1662021-01-29 10:08:50 -05002061 Modifiers(Layout(/*flags=*/0, /*location=*/-1,
John Stiles270cec22021-02-17 12:59:36 -05002062 fProgram.fConfig->fSettings.fRTHeightOffset,
John Stilese40d1662021-01-29 10:08:50 -05002063 /*binding=*/-1, /*index=*/-1, /*set=*/-1, /*builtin=*/-1,
Brian Osman4717fbb2021-02-23 13:12:09 -05002064 /*inputAttachmentIndex=*/-1,
John Stilese40d1662021-01-29 10:08:50 -05002065 Layout::kUnspecified_Primitive, /*maxVertices=*/1,
Brian Osman8f1dff62021-04-19 13:50:58 -04002066 /*invocations=*/-1, /*when=*/"", Layout::CType::kDefault),
John Stilese40d1662021-01-29 10:08:50 -05002067 /*flags=*/0),
John Stiles54e7c052021-01-11 14:22:36 -05002068 SKSL_RTHEIGHT_NAME, fContext.fTypes.fFloat.get());
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002069 String name("sksl_synthetic_uniforms");
John Stilesad2d4942020-12-11 16:55:58 -05002070 std::unique_ptr<Type> intfStruct = Type::MakeStructType(/*offset=*/-1, name,
2071 fields);
John Stiles270cec22021-02-17 12:59:36 -05002072 int binding = fProgram.fConfig->fSettings.fRTHeightBinding;
John Stiles5570c512020-11-19 17:58:07 -05002073 if (binding == -1) {
2074 fErrors.error(ref.fOffset, "layout(binding=...) is required in SPIR-V");
2075 }
John Stiles270cec22021-02-17 12:59:36 -05002076 int set = fProgram.fConfig->fSettings.fRTHeightSet;
John Stiles5570c512020-11-19 17:58:07 -05002077 if (set == -1) {
2078 fErrors.error(ref.fOffset, "layout(set=...) is required in SPIR-V");
2079 }
John Stiles270cec22021-02-17 12:59:36 -05002080 bool usePushConstants = fProgram.fConfig->fSettings.fUsePushConstants;
John Stilese40d1662021-01-29 10:08:50 -05002081 int flags = usePushConstants ? Layout::Flag::kPushConstant_Flag : 0;
2082 Modifiers modifiers(
2083 Layout(flags, /*location=*/-1, /*offset=*/-1, binding, /*index=*/-1,
2084 set, /*builtin=*/-1, /*inputAttachmentIndex=*/-1,
Brian Osman4717fbb2021-02-23 13:12:09 -05002085 Layout::kUnspecified_Primitive,
Brian Osman8f1dff62021-04-19 13:50:58 -04002086 /*maxVertices=*/-1, /*invocations=*/-1, /*when=*/"",
Brian Osmanba7ef322021-02-23 13:37:22 -05002087 Layout::CType::kDefault),
John Stilese40d1662021-01-29 10:08:50 -05002088 Modifiers::kUniform_Flag);
John Stiles3ae071e2020-08-05 15:29:29 -04002089 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
2090 std::make_unique<Variable>(/*offset=*/-1,
John Stilesf2872e62021-05-04 11:38:43 -04002091 fProgram.fModifiers->add(modifiers),
John Stiles3ae071e2020-08-05 15:29:29 -04002092 name,
John Stilesad2d4942020-12-11 16:55:58 -05002093 intfStruct.get(),
Brian Osman3887a012020-09-30 13:22:27 -04002094 /*builtin=*/false,
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002095 Variable::Storage::kGlobal));
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002096 InterfaceBlock intf(/*offset=*/-1,
2097 intfVar,
2098 name,
2099 /*instanceName=*/"",
2100 /*arraySize=*/0,
John Stiles7c3515b2020-10-16 18:38:39 -04002101 std::make_shared<SymbolTable>(&fErrors, /*builtin=*/false));
Stephen White88574972020-06-23 19:09:29 -04002102
2103 fRTHeightStructId = this->writeInterfaceBlock(intf, false);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002104 fRTHeightFieldIndex = 0;
Jim Van Verth46e9b0e2021-01-28 17:26:48 -05002105 fRTHeightStorageClass = usePushConstants ? SpvStorageClassPushConstant
2106 : SpvStorageClassUniform;
Greg Daniela85e4bf2020-06-17 16:32:45 -04002107 }
2108 SkASSERT(fRTHeightFieldIndex != (SpvId)-1);
2109
John Stiles9ce80f72021-03-11 22:35:19 -05002110 IntLiteral fieldIndex(/*offset=*/-1, fRTHeightFieldIndex, fContext.fTypes.fInt.get());
Greg Daniela85e4bf2020-06-17 16:32:45 -04002111 SpvId fieldIndexId = this->writeIntLiteral(fieldIndex);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002112 SpvId heightPtr = this->nextId(nullptr);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002113 this->writeOpCode(SpvOpAccessChain, 5, out);
John Stiles54e7c052021-01-11 14:22:36 -05002114 this->writeWord(this->getPointerType(*fContext.fTypes.fFloat, fRTHeightStorageClass),
Greg Daniela85e4bf2020-06-17 16:32:45 -04002115 out);
2116 this->writeWord(heightPtr, out);
2117 this->writeWord(fRTHeightStructId, out);
2118 this->writeWord(fieldIndexId, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002119 SpvId heightRead = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002120 this->writeInstruction(SpvOpLoad, this->getType(*fContext.fTypes.fFloat), heightRead,
Greg Daniela85e4bf2020-06-17 16:32:45 -04002121 heightPtr, out);
2122
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002123 flippedYId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002124 this->writeInstruction(SpvOpFSub, this->getType(*fContext.fTypes.fFloat), flippedYId,
Greg Daniela85e4bf2020-06-17 16:32:45 -04002125 heightRead, rawYId, out);
2126 }
2127
2128 // The z component will always be zero so we just get an id to the 0 literal
John Stiles9ce80f72021-03-11 22:35:19 -05002129 FloatLiteral zero(/*offset=*/-1, /*value=*/0.0, fContext.fTypes.fFloat.get());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002130 SpvId zeroId = writeFloatLiteral(zero);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002131
Brian Osmane38bedd2020-12-21 11:51:54 -05002132 // Calculate the w component
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002133 SpvId rawWId = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002134 this->writeInstruction(SpvOpCompositeExtract, this->getType(*fContext.fTypes.fFloat),
2135 rawWId, result, 3, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002136
2137 // Fill in the new fragcoord with the components from above
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002138 SpvId adjusted = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002139 this->writeOpCode(SpvOpCompositeConstruct, 7, out);
John Stiles54e7c052021-01-11 14:22:36 -05002140 this->writeWord(this->getType(*fContext.fTypes.fFloat4), out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002141 this->writeWord(adjusted, out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002142 this->writeWord(xId, out);
John Stiles270cec22021-02-17 12:59:36 -05002143 if (fProgram.fConfig->fSettings.fFlipY) {
Greg Daniela85e4bf2020-06-17 16:32:45 -04002144 this->writeWord(flippedYId, out);
2145 } else {
2146 this->writeWord(rawYId, out);
2147 }
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002148 this->writeWord(zeroId, out);
Brian Osmane38bedd2020-12-21 11:51:54 -05002149 this->writeWord(rawWId, out);
Greg Daniela85e4bf2020-06-17 16:32:45 -04002150
2151 return adjusted;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002152 }
John Stiles1e1fe122021-01-29 12:18:46 -05002153
2154 // Handle the "flipY" setting when reading sk_Clockwise.
John Stilese40d1662021-01-29 10:08:50 -05002155 if (variable->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN &&
John Stiles270cec22021-02-17 12:59:36 -05002156 !fProgram.fConfig->fSettings.fFlipY) {
Chris Daltonb91c4662018-08-01 10:46:22 -06002157 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia, we use
2158 // the default convention of "counter-clockwise face is front".
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002159 SpvId inverse = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002160 this->writeInstruction(SpvOpLogicalNot, this->getType(*fContext.fTypes.fBool), inverse,
Chris Daltonb91c4662018-08-01 10:46:22 -06002161 result, out);
2162 return inverse;
2163 }
John Stiles1e1fe122021-01-29 12:18:46 -05002164
ethannicholasb3058bd2016-07-01 08:22:01 -07002165 return result;
2166}
2167
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002168SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002169 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002170 SpvId base = this->writeExpression(*expr.base(), out);
2171 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002172 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002173 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002174 index, out);
2175 return result;
2176 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002177 return getLValue(expr, out)->load(out);
2178}
2179
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002180SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002181 return getLValue(f, out)->load(out);
2182}
2183
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002184SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002185 SpvId base = this->writeExpression(*swizzle.base(), out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002186 SpvId result = this->nextId(&swizzle.type());
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002187 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002188 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002189 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002190 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002191 } else {
2192 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002193 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002194 this->writeWord(result, out);
2195 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002196 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002197 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002198 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002199 }
2200 }
2201 return result;
2202}
2203
Greg Daniel64773e62016-11-22 09:44:03 -05002204SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2205 const Type& operandType, SpvId lhs,
2206 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002207 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002208 SpvId result = this->nextId(&resultType);
ethannicholasd598f792016-07-25 10:08:54 -07002209 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002210 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002211 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002212 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002213 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002214 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002215 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002216 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2217 } else {
John Stiles123501f2020-12-09 10:08:13 -05002218 fErrors.error(operandType.fOffset,
2219 "unsupported operand for binary expression: " + operandType.description());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002220 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002221 return result;
2222}
2223
Ethan Nicholas48e24052018-03-14 13:51:39 -04002224SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2225 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002226 if (operandType.isVector()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002227 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002228 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002229 return result;
2230 }
2231 return id;
2232}
2233
Ethan Nicholas68990be2017-07-13 09:36:52 -04002234SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2235 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002236 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002237 OutputStream& out) {
2238 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002239 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002240 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2241 operandType.rows(),
2242 1));
John Stiles54e7c052021-01-11 14:22:36 -05002243 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002244 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002245 1));
John Stiles54e7c052021-01-11 14:22:36 -05002246 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002247 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002248 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002249 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002250 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002251 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002252 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002253 SpvId compare = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002254 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002255 SpvId merge = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002256 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002257 if (result != 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002258 SpvId next = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002259 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002260 result = next;
2261 }
2262 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002263 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002264 }
2265 }
2266 return result;
2267}
2268
Ethan Nicholas0df21132018-07-10 09:37:51 -04002269SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
John Stiles43b593c2021-05-13 22:03:27 -04002270 SpvId rhs, SpvOp_ op, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002271 SkASSERT(operandType.isMatrix());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002272 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2273 operandType.rows(),
2274 1));
John Stiles43b593c2021-05-13 22:03:27 -04002275 std::vector<SpvId> columns;
2276 columns.reserve(operandType.columns());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002277 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002278 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002279 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002280 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002281 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
John Stiles43b593c2021-05-13 22:03:27 -04002282 columns.push_back(this->nextId(&operandType));
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002283 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002284 }
John Stiles43b593c2021-05-13 22:03:27 -04002285 return this->writeComposite(columns, operandType, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002286}
2287
John Stiles9485b552021-01-27 11:47:00 -05002288static std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002289 if (type.isInteger()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002290 return IntLiteral::Make(/*offset=*/-1, /*value=*/1, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002291 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002292 else if (type.isFloat()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002293 return FloatLiteral::Make(/*offset=*/-1, /*value=*/1.0, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002294 } else {
John Stilesf57207b2021-02-02 17:50:34 -05002295 SK_ABORT("math is unsupported on type '%s'", String(type.name()).c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -07002296 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002297}
2298
John Stilesd94bfdd2021-03-25 11:44:08 -04002299SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, OutputStream& out) {
2300 SkASSERT(type.isFloat());
2301 SpvId one = this->writeFloatLiteral({/*offset=*/-1, /*value=*/1, &type});
2302 SpvId reciprocal = this->nextId(&type);
2303 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
2304 return reciprocal;
2305}
2306
John Stilesa91bf052021-05-17 09:34:03 -04002307SpvId SPIRVCodeGenerator::writeScalarToMatrixSplat(const Type& matrixType,
2308 SpvId scalarId,
2309 OutputStream& out) {
2310 // Splat the scalar into a vector.
2311 const Type& vectorType = matrixType.componentType().toCompound(fContext,
2312 /*columns=*/matrixType.rows(),
2313 /*rows=*/1);
2314 std::vector<SpvId> vecArguments(/*count*/ matrixType.rows(), /*value*/ scalarId);
2315 SpvId vectorId = this->writeComposite(vecArguments, vectorType, out);
2316
2317 // Splat the vector into a matrix.
2318 std::vector<SpvId> matArguments(/*count*/ matrixType.columns(), /*value*/ vectorId);
2319 return this->writeComposite(matArguments, matrixType, out);
2320}
2321
John Stiles45990502021-02-16 10:55:27 -05002322SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
Ethan Nicholas49465b42019-04-17 12:22:21 -04002323 const Type& rightType, SpvId rhs,
2324 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002325 // The comma operator ignores the type of the left-hand side entirely.
John Stiles45990502021-02-16 10:55:27 -05002326 if (op.kind() == Token::Kind::TK_COMMA) {
John Stilesd0614f22020-12-09 11:11:41 -05002327 return rhs;
2328 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002329 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002330 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002331 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2332 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002333 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002334 if (leftType.isVector() && rightType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002335 if (resultType.componentType().isFloat()) {
2336 switch (op.kind()) {
2337 case Token::Kind::TK_SLASH: {
2338 rhs = this->writeReciprocal(rightType, rhs, out);
2339 [[fallthrough]];
2340 }
2341 case Token::Kind::TK_STAR: {
2342 SpvId result = this->nextId(&resultType);
2343 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2344 result, lhs, rhs, out);
2345 return result;
2346 }
2347 default:
2348 break;
2349 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002350 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002351 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002352 const Type& vecType = leftType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002353 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002354 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2355 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002356 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002357 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002358 this->writeWord(rhs, out);
2359 }
2360 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002361 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002362 } else if (rightType.isVector() && leftType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002363 if (resultType.componentType().isFloat()) {
2364 if (op.kind() == Token::Kind::TK_STAR) {
2365 SpvId result = this->nextId(&resultType);
2366 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2367 result, rhs, lhs, out);
2368 return result;
2369 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002370 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002371 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002372 const Type& vecType = rightType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002373 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002374 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2375 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002376 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002377 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002378 this->writeWord(lhs, out);
2379 }
2380 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002381 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002382 } else if (leftType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002383 if (op.kind() == Token::Kind::TK_STAR) {
2384 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2385 SpvOp_ spvop;
2386 if (rightType.isMatrix()) {
2387 spvop = SpvOpMatrixTimesMatrix;
2388 } else if (rightType.isVector()) {
2389 spvop = SpvOpMatrixTimesVector;
2390 } else {
2391 SkASSERT(rightType.isScalar());
2392 spvop = SpvOpMatrixTimesScalar;
2393 }
2394 SpvId result = this->nextId(&resultType);
2395 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
2396 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002397 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002398 // Matrix-op-vector is not supported in GLSL/SkSL for non-multiplication ops; we
2399 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002400 SkASSERT(rightType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002401
2402 // Splat rhs across an entire matrix so we can reuse the matrix-op-matrix path.
2403 SpvId rhsMatrix = this->writeScalarToMatrixSplat(leftType, rhs, out);
2404
2405 // Perform this operation as matrix-op-matrix.
2406 return this->writeBinaryExpression(leftType, lhs, op, leftType, rhsMatrix,
2407 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002408 }
John Stiles9aeed132020-11-24 17:36:06 -05002409 } else if (rightType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002410 if (op.kind() == Token::Kind::TK_STAR) {
2411 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2412 SpvId result = this->nextId(&resultType);
2413 if (leftType.isVector()) {
2414 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType),
2415 result, lhs, rhs, out);
2416 } else {
2417 SkASSERT(leftType.isScalar());
2418 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType),
2419 result, rhs, lhs, out);
2420 }
2421 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002422 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002423 // Vector-op-matrix is not supported in GLSL/SkSL for non-multiplication ops; we
2424 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002425 SkASSERT(leftType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002426
2427 // Splat lhs across an entire matrix so we can reuse the matrix-op-matrix path.
2428 SpvId lhsMatrix = this->writeScalarToMatrixSplat(rightType, lhs, out);
2429
2430 // Perform this operation as matrix-op-matrix.
2431 return this->writeBinaryExpression(rightType, lhsMatrix, op, rightType, rhs,
2432 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002433 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002434 } else {
John Stilesd8ca6b62020-11-23 14:28:36 -05002435 fErrors.error(leftType.fOffset, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002436 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002437 }
2438 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002439 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002440 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002441 }
John Stiles45990502021-02-16 10:55:27 -05002442 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002443 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002444 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002445 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002446 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002447 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002448 if (operandType->isStruct()) {
2449 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2450 }
John Stiles35092102021-04-08 23:30:51 -04002451 if (operandType->isArray()) {
2452 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2453 }
John Stiles4a7dc462020-11-25 11:08:08 -05002454 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002455 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002456 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002457 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2458 operandType->columns(),
2459 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002460 } else {
2461 tmpType = &resultType;
2462 }
2463 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002464 SpvOpFOrdEqual, SpvOpIEqual,
2465 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002466 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002467 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002468 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002469 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002470 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002471 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002472 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002473 if (operandType->isStruct()) {
2474 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2475 }
John Stiles35092102021-04-08 23:30:51 -04002476 if (operandType->isArray()) {
2477 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2478 }
John Stiles4a7dc462020-11-25 11:08:08 -05002479 [[fallthrough]];
2480 case Token::Kind::TK_LOGICALXOR:
2481 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002482 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002483 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002484 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2485 operandType->columns(),
2486 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002487 } else {
2488 tmpType = &resultType;
2489 }
2490 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002491 SpvOpFOrdNotEqual, SpvOpINotEqual,
2492 SpvOpINotEqual, SpvOpLogicalNotEqual,
2493 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002494 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002495 case Token::Kind::TK_GT:
John Stiles4a7dc462020-11-25 11:08:08 -05002496 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002497 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2498 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002499 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002500 case Token::Kind::TK_LT:
John Stiles4a7dc462020-11-25 11:08:08 -05002501 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002502 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002503 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002504 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002505 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002506 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2507 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002508 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002509 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002510 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002511 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2512 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002513 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002514 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002515 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002516 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002517 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFAdd, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002518 }
Greg Daniel64773e62016-11-22 09:44:03 -05002519 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002520 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002521 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002522 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002523 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002524 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFSub, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002525 }
Greg Daniel64773e62016-11-22 09:44:03 -05002526 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002527 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002528 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002529 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002530 // matrix multiply
Ethan Nicholas7f015882021-03-23 14:16:52 -04002531 SpvId result = this->nextId(&resultType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002532 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2533 lhs, rhs, out);
2534 return result;
2535 }
Greg Daniel64773e62016-11-22 09:44:03 -05002536 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002537 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002538 case Token::Kind::TK_SLASH:
John Stilesbdf3bb72021-05-17 09:34:23 -04002539 if (leftType.isMatrix() && rightType.isMatrix()) {
2540 SkASSERT(leftType == rightType);
2541 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFDiv, out);
2542 }
Greg Daniel64773e62016-11-22 09:44:03 -05002543 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002544 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002545 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002546 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2547 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002548 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002549 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2550 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2551 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002552 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002553 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2554 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2555 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002556 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002557 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2558 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002559 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002560 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2561 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002562 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002563 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2564 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002565 default:
John Stiles5570c512020-11-19 17:58:07 -05002566 fErrors.error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002567 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002568 }
2569}
2570
John Stiles35092102021-04-08 23:30:51 -04002571SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
2572 SpvId rhs, OutputStream& out) {
2573 // The inputs must be arrays, and the op must be == or !=.
2574 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
2575 SkASSERT(arrayType.isArray());
2576 const Type& componentType = arrayType.componentType();
2577 const SpvId componentTypeId = this->getType(componentType);
2578 const int arraySize = arrayType.columns();
2579 SkASSERT(arraySize > 0);
2580
2581 // Synthesize equality checks for each item in the array.
2582 const Type& boolType = *fContext.fTypes.fBool;
2583 SpvId allComparisons = (SpvId)-1;
2584 for (int index = 0; index < arraySize; ++index) {
2585 // Get the left and right item in the array.
2586 SpvId itemL = this->nextId(&componentType);
2587 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemL, lhs, index, out);
2588 SpvId itemR = this->nextId(&componentType);
2589 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemR, rhs, index, out);
2590 // Use `writeBinaryExpression` with the requested == or != operator on these items.
2591 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
2592 componentType, itemR, boolType, out);
2593 // Merge this comparison result with all the other comparisons we've done.
2594 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
2595 }
2596 return allComparisons;
2597}
2598
John Stilesbc5c2a02021-04-08 11:44:53 -04002599SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
2600 SpvId rhs, OutputStream& out) {
2601 // The inputs must be structs containing fields, and the op must be == or !=.
John Stilesbc5c2a02021-04-08 11:44:53 -04002602 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
John Stiles35092102021-04-08 23:30:51 -04002603 SkASSERT(structType.isStruct());
John Stilesbc5c2a02021-04-08 11:44:53 -04002604 const std::vector<Type::Field>& fields = structType.fields();
2605 SkASSERT(!fields.empty());
2606
2607 // Synthesize equality checks for each field in the struct.
2608 const Type& boolType = *fContext.fTypes.fBool;
John Stilesbc5c2a02021-04-08 11:44:53 -04002609 SpvId allComparisons = (SpvId)-1;
2610 for (int index = 0; index < (int)fields.size(); ++index) {
2611 // Get the left and right versions of this field.
2612 const Type& fieldType = *fields[index].fType;
John Stiles35092102021-04-08 23:30:51 -04002613 const SpvId fieldTypeId = this->getType(fieldType);
John Stilesbc5c2a02021-04-08 11:44:53 -04002614
2615 SpvId fieldL = this->nextId(&fieldType);
2616 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldL, lhs, index, out);
2617 SpvId fieldR = this->nextId(&fieldType);
2618 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldR, rhs, index, out);
2619 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
2620 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
2621 boolType, out);
John Stiles35092102021-04-08 23:30:51 -04002622 // Merge this comparison result with all the other comparisons we've done.
2623 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002624 }
2625 return allComparisons;
2626}
2627
John Stiles35092102021-04-08 23:30:51 -04002628SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
2629 OutputStream& out) {
2630 // If this is the first entry, we don't need to merge comparison results with anything.
2631 if (allComparisons == (SpvId)-1) {
2632 return comparison;
2633 }
2634 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
2635 const Type& boolType = *fContext.fTypes.fBool;
2636 SpvId boolTypeId = this->getType(boolType);
2637 SpvId logicalOp = this->nextId(&boolType);
2638 switch (op.kind()) {
2639 case Token::Kind::TK_EQEQ:
2640 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
2641 comparison, allComparisons, out);
2642 break;
2643 case Token::Kind::TK_NEQ:
2644 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
2645 comparison, allComparisons, out);
2646 break;
2647 default:
2648 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
2649 return (SpvId)-1;
2650 }
2651 return logicalOp;
2652}
2653
John Stilesbc5c2a02021-04-08 11:44:53 -04002654static float division_by_literal_value(Operator op, const Expression& right) {
2655 // If this is a division by a literal value, returns that literal value. Otherwise, returns 0.
2656 if (op.kind() == Token::Kind::TK_SLASH && right.is<FloatLiteral>()) {
2657 float rhsValue = right.as<FloatLiteral>().value();
2658 if (std::isfinite(rhsValue)) {
2659 return rhsValue;
2660 }
2661 }
2662 return 0.0f;
2663}
2664
Ethan Nicholas49465b42019-04-17 12:22:21 -04002665SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2396fb82021-03-25 11:44:55 -04002666 const Expression* left = b.left().get();
2667 const Expression* right = b.right().get();
John Stiles45990502021-02-16 10:55:27 -05002668 Operator op = b.getOperator();
John Stilesbc5c2a02021-04-08 11:44:53 -04002669
John Stiles45990502021-02-16 10:55:27 -05002670 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002671 case Token::Kind::TK_EQ: {
John Stilesbc5c2a02021-04-08 11:44:53 -04002672 // Handles assignment.
John Stiles2396fb82021-03-25 11:44:55 -04002673 SpvId rhs = this->writeExpression(*right, out);
2674 this->getLValue(*left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002675 return rhs;
2676 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002677 case Token::Kind::TK_LOGICALAND:
John Stilesbc5c2a02021-04-08 11:44:53 -04002678 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2679 return this->writeLogicalAnd(*b.left(), *b.right(), out);
2680
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002681 case Token::Kind::TK_LOGICALOR:
John Stilesbc5c2a02021-04-08 11:44:53 -04002682 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2683 return this->writeLogicalOr(*b.left(), *b.right(), out);
2684
Ethan Nicholas49465b42019-04-17 12:22:21 -04002685 default:
2686 break;
2687 }
2688
2689 std::unique_ptr<LValue> lvalue;
2690 SpvId lhs;
John Stiles45990502021-02-16 10:55:27 -05002691 if (op.isAssignment()) {
John Stiles2396fb82021-03-25 11:44:55 -04002692 lvalue = this->getLValue(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002693 lhs = lvalue->load(out);
2694 } else {
2695 lvalue = nullptr;
John Stiles2396fb82021-03-25 11:44:55 -04002696 lhs = this->writeExpression(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002697 }
John Stiles2396fb82021-03-25 11:44:55 -04002698
John Stilesbc5c2a02021-04-08 11:44:53 -04002699 SpvId rhs;
2700 float rhsValue = division_by_literal_value(op, *right);
2701 if (rhsValue != 0.0f) {
2702 // Rewrite floating-point division by a literal into multiplication by the reciprocal.
2703 // This converts `expr / 2` into `expr * 0.5`
2704 // This improves codegen, especially for certain types of divides (e.g. vector/scalar).
2705 op = Operator(Token::Kind::TK_STAR);
2706 FloatLiteral reciprocal{right->fOffset, 1.0f / rhsValue, &right->type()};
2707 rhs = this->writeExpression(reciprocal, out);
2708 } else {
2709 // Write the right-hand side expression normally.
John Stiles2396fb82021-03-25 11:44:55 -04002710 rhs = this->writeExpression(*right, out);
2711 }
2712
2713 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
2714 right->type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002715 if (lvalue) {
2716 lvalue->store(result, out);
2717 }
2718 return result;
2719}
2720
John Stilesbc5c2a02021-04-08 11:44:53 -04002721SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
2722 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002723 BoolLiteral falseLiteral(/*offset=*/-1, /*value=*/false, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002724 SpvId falseConstant = this->writeBoolLiteral(falseLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002725 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002726 SpvId rhsLabel = this->nextId(nullptr);
2727 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002728 SpvId lhsBlock = fCurrentBlock;
2729 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2730 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2731 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002732 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002733 SpvId rhsBlock = fCurrentBlock;
2734 this->writeInstruction(SpvOpBranch, end, out);
2735 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002736 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002737 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002738 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002739 return result;
2740}
2741
John Stilesbc5c2a02021-04-08 11:44:53 -04002742SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
2743 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002744 BoolLiteral trueLiteral(/*offset=*/-1, /*value=*/true, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002745 SpvId trueConstant = this->writeBoolLiteral(trueLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002746 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002747 SpvId rhsLabel = this->nextId(nullptr);
2748 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002749 SpvId lhsBlock = fCurrentBlock;
2750 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2751 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2752 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002753 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002754 SpvId rhsBlock = fCurrentBlock;
2755 this->writeInstruction(SpvOpBranch, end, out);
2756 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002757 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002758 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002759 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002760 return result;
2761}
2762
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002763SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002764 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002765 SpvId test = this->writeExpression(*t.test(), out);
2766 if (t.ifTrue()->type().columns() == 1 &&
2767 t.ifTrue()->isCompileTimeConstant() &&
2768 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002769 // both true and false are constants, can just use OpSelect
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002770 SpvId result = this->nextId(nullptr);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002771 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2772 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002773 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002774 out);
2775 return result;
2776 }
Greg Daniel64773e62016-11-22 09:44:03 -05002777 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002778 // Adreno. Switched to storing the result in a temp variable as glslang does.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002779 SpvId var = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002780 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002781 var, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002782 SpvId trueLabel = this->nextId(nullptr);
2783 SpvId falseLabel = this->nextId(nullptr);
2784 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002785 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2786 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2787 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002788 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002789 this->writeInstruction(SpvOpBranch, end, out);
2790 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002791 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002792 this->writeInstruction(SpvOpBranch, end, out);
2793 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002794 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002795 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002796 return result;
2797}
2798
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002799SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002800 const Type& type = p.type();
John Stiles45990502021-02-16 10:55:27 -05002801 if (p.getOperator().kind() == Token::Kind::TK_MINUS) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002802 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002803 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002804 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002805 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002806 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002807 } else if (is_signed(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002808 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2809 } else {
John Stileseada7bc2021-02-02 16:29:32 -05002810 SkDEBUGFAILF("unsupported prefix expression %s", p.description().c_str());
Brian Salomon23356442018-11-30 15:33:19 -05002811 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002812 return result;
2813 }
John Stiles45990502021-02-16 10:55:27 -05002814 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002815 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002816 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002817 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002818 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002819 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2820 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one,
Greg Daniel64773e62016-11-22 09:44:03 -05002821 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002822 out);
2823 lv->store(result, out);
2824 return result;
2825 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002826 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002827 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002828 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2829 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2830 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002831 lv->store(result, out);
2832 return result;
2833 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002834 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002835 SkASSERT(p.operand()->type().isBoolean());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002836 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002837 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2838 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002839 return result;
2840 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002841 case Token::Kind::TK_BITWISENOT: {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002842 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002843 this->writeInstruction(SpvOpNot, this->getType(type), result,
2844 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002845 return result;
2846 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002847 default:
John Stileseada7bc2021-02-02 16:29:32 -05002848 SkDEBUGFAILF("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002849 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002850 }
2851}
2852
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002853SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002854 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002855 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002856 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002857 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
John Stiles45990502021-02-16 10:55:27 -05002858 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002859 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002860 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002861 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2862 lv->store(temp, out);
2863 return result;
2864 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002865 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002866 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002867 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2868 lv->store(temp, out);
2869 return result;
2870 }
2871 default:
John Stileseada7bc2021-02-02 16:29:32 -05002872 SkDEBUGFAILF("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002873 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002874 }
2875}
2876
ethannicholasf789b382016-08-03 12:43:36 -07002877SpvId SPIRVCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002878 if (b.value()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002879 if (fBoolTrue == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002880 fBoolTrue = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002881 this->writeInstruction(SpvOpConstantTrue, this->getType(b.type()), fBoolTrue,
ethannicholasb3058bd2016-07-01 08:22:01 -07002882 fConstantBuffer);
2883 }
2884 return fBoolTrue;
2885 } else {
2886 if (fBoolFalse == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002887 fBoolFalse = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002888 this->writeInstruction(SpvOpConstantFalse, this->getType(b.type()), fBoolFalse,
ethannicholasb3058bd2016-07-01 08:22:01 -07002889 fConstantBuffer);
2890 }
2891 return fBoolFalse;
2892 }
2893}
2894
ethannicholasf789b382016-08-03 12:43:36 -07002895SpvId SPIRVCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002896 SPIRVNumberConstant key{i.value(), i.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002897 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2898 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002899 SpvId result = this->nextId(nullptr);
John Stilesacb091f2021-01-06 11:57:58 -05002900 this->writeInstruction(SpvOpConstant, this->getType(i.type()), result, (SpvId) i.value(),
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002901 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002902 iter->second = result;
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002903 }
John Stilesacb091f2021-01-06 11:57:58 -05002904 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002905}
2906
ethannicholasf789b382016-08-03 12:43:36 -07002907SpvId SPIRVCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002908 // Convert the float literal into its bit-representation.
2909 float value = f.value();
2910 uint32_t valueBits;
2911 static_assert(sizeof(valueBits) == sizeof(value));
2912 memcpy(&valueBits, &value, sizeof(value));
2913
2914 SPIRVNumberConstant key{valueBits, f.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002915 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2916 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002917 SpvId result = this->nextId(nullptr);
John Stilesbdc3d3c2021-01-06 18:41:40 -05002918 this->writeInstruction(SpvOpConstant, this->getType(f.type()), result, (SpvId) valueBits,
John Stiles8c578662020-06-01 15:32:47 +00002919 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002920 iter->second = result;
John Stiles8c578662020-06-01 15:32:47 +00002921 }
John Stilesacb091f2021-01-06 11:57:58 -05002922 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002923}
2924
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002925SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002926 SpvId result = fFunctionMap[&f];
John Stilesb5db4822021-01-21 13:04:40 -05002927 SpvId returnTypeId = this->getType(f.returnType());
2928 SpvId functionTypeId = this->getFunctionType(f);
2929 this->writeInstruction(SpvOpFunction, returnTypeId, result,
2930 SpvFunctionControlMaskNone, functionTypeId, out);
John Stilesf9e85512021-03-22 12:05:31 -04002931 String mangledName = f.mangledName();
2932 this->writeInstruction(SpvOpName,
2933 result,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002934 skstd::string_view(mangledName.c_str(), mangledName.size()),
John Stilesf9e85512021-03-22 12:05:31 -04002935 fNameBuffer);
2936 for (const Variable* parameter : f.parameters()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002937 SpvId id = this->nextId(nullptr);
John Stilesf9e85512021-03-22 12:05:31 -04002938 fVariableMap[parameter] = id;
2939 SpvId type = this->getPointerType(parameter->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002940 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2941 }
2942 return result;
2943}
2944
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002945SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2946 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002947 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002948 fCurrentBlock = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002949 this->writeLabel(this->nextId(nullptr), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002950 StringStream bodyBuffer;
John Stiles0693fb82021-01-22 18:27:52 -05002951 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002952 write_stringstream(fVariableBuffer, out);
John Stilese8da4d22021-03-24 09:19:45 -04002953 if (f.declaration().isMain()) {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002954 write_stringstream(fGlobalInitializersBuffer, out);
2955 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002956 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002957 if (fCurrentBlock) {
John Stiles2558c462021-03-16 17:49:20 -04002958 if (f.declaration().returnType().isVoid()) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002959 this->writeInstruction(SpvOpReturn, out);
2960 } else {
2961 this->writeInstruction(SpvOpUnreachable, out);
2962 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002963 }
2964 this->writeInstruction(SpvOpFunctionEnd, out);
2965 return result;
2966}
2967
2968void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2969 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002970 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002971 fDecorationBuffer);
2972 }
2973 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002974 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002975 fDecorationBuffer);
2976 }
2977 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002978 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002979 fDecorationBuffer);
2980 }
2981 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002982 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002983 fDecorationBuffer);
2984 }
Greg Daniel64773e62016-11-22 09:44:03 -05002985 if (layout.fInputAttachmentIndex >= 0) {
2986 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2987 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002988 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002989 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04002990 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN &&
Greg Daniele6ab9982018-08-22 13:56:32 +00002991 layout.fBuiltin != SK_IN_BUILTIN && layout.fBuiltin != SK_OUT_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002992 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002993 fDecorationBuffer);
2994 }
2995}
2996
2997void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2998 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002999 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07003000 layout.fLocation, fDecorationBuffer);
3001 }
3002 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003003 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07003004 layout.fBinding, fDecorationBuffer);
3005 }
3006 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003007 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07003008 layout.fIndex, fDecorationBuffer);
3009 }
3010 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003011 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07003012 layout.fSet, fDecorationBuffer);
3013 }
Greg Daniel64773e62016-11-22 09:44:03 -05003014 if (layout.fInputAttachmentIndex >= 0) {
3015 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
3016 layout.fInputAttachmentIndex, fDecorationBuffer);
3017 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003018 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003019 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07003020 layout.fBuiltin, fDecorationBuffer);
3021 }
3022}
3023
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003024MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003025 bool pushConstant = ((v.modifiers().fLayout.fFlags & Layout::kPushConstant_Flag) != 0);
Brian Osman58ee8982021-02-18 15:39:38 -05003026 return pushConstant ? MemoryLayout(MemoryLayout::k430_Standard) : fDefaultLayout;
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003027}
3028
Ethan Nicholas81d15112018-07-13 12:48:50 -04003029static void update_sk_in_count(const Modifiers& m, int* outSkInCount) {
3030 switch (m.fLayout.fPrimitive) {
3031 case Layout::kPoints_Primitive:
3032 *outSkInCount = 1;
3033 break;
3034 case Layout::kLines_Primitive:
3035 *outSkInCount = 2;
3036 break;
3037 case Layout::kLinesAdjacency_Primitive:
3038 *outSkInCount = 4;
3039 break;
3040 case Layout::kTriangles_Primitive:
3041 *outSkInCount = 3;
3042 break;
3043 case Layout::kTrianglesAdjacency_Primitive:
3044 *outSkInCount = 6;
3045 break;
3046 default:
3047 return;
3048 }
3049}
3050
Stephen White88574972020-06-23 19:09:29 -04003051SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTHeight) {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003052 MemoryLayout memoryLayout = this->memoryLayoutForVariable(intf.variable());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003053 SpvId result = this->nextId(nullptr);
John Stilesad2d4942020-12-11 16:55:58 -05003054 std::unique_ptr<Type> rtHeightStructType;
Ethan Nicholaseaf47882020-10-15 10:10:08 -04003055 const Type* type = &intf.variable().type();
John Stiles21f5f452020-11-30 09:57:59 -05003056 if (!MemoryLayout::LayoutIsSupported(*type)) {
John Stiles0023c0c2020-11-16 13:32:18 -05003057 fErrors.error(type->fOffset, "type '" + type->name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003058 return this->nextId(nullptr);
John Stiles0023c0c2020-11-16 13:32:18 -05003059 }
John Stiles9485b552021-01-27 11:47:00 -05003060 SpvStorageClass_ storageClass = get_storage_class(intf.variable(), SpvStorageClassFunction);
Stephen White88574972020-06-23 19:09:29 -04003061 if (fProgram.fInputs.fRTHeight && appendRTHeight) {
Greg Daniele6ab9982018-08-22 13:56:32 +00003062 SkASSERT(fRTHeightStructId == (SpvId) -1);
3063 SkASSERT(fRTHeightFieldIndex == (SpvId) -1);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003064 std::vector<Type::Field> fields = type->fields();
Greg Daniele6ab9982018-08-22 13:56:32 +00003065 fRTHeightStructId = result;
3066 fRTHeightFieldIndex = fields.size();
Jim Van Verthf3ec9832020-10-21 16:09:57 -04003067 fRTHeightStorageClass = storageClass;
Ethan Nicholas962dec42021-06-10 13:06:39 -04003068 fields.emplace_back(Modifiers(), skstd::string_view(SKSL_RTHEIGHT_NAME),
John Stiles54e7c052021-01-11 14:22:36 -05003069 fContext.fTypes.fFloat.get());
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003070 rtHeightStructType = Type::MakeStructType(type->fOffset, String(type->name()),
3071 std::move(fields));
John Stilesad2d4942020-12-11 16:55:58 -05003072 type = rtHeightStructType.get();
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003073 }
Ethan Nicholas5226b772018-05-03 16:20:41 -04003074 SpvId typeId;
John Stiles9485b552021-01-27 11:47:00 -05003075 const Modifiers& intfModifiers = intf.variable().modifiers();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003076 if (intfModifiers.fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osman133724c2020-10-28 14:14:39 -04003077 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003078 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003079 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholas81d15112018-07-13 12:48:50 -04003080 update_sk_in_count(m, &fSkInCount);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003081 }
3082 }
John Stilesad2d4942020-12-11 16:55:58 -05003083 typeId = this->getType(
3084 *Type::MakeArrayType("sk_in", intf.variable().type().componentType(), fSkInCount),
3085 memoryLayout);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003086 } else {
3087 typeId = this->getType(*type, memoryLayout);
3088 }
Brian Osman58ee8982021-02-18 15:39:38 -05003089 if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00003090 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04003091 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003092 SpvId ptrType = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003093 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003094 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003095 Layout layout = intfModifiers.fLayout;
3096 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04003097 layout.fSet = 0;
3098 }
3099 this->writeLayout(layout, result);
Ethan Nicholaseaf47882020-10-15 10:10:08 -04003100 fVariableMap[&intf.variable()] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07003101 return result;
3102}
3103
John Stiles9485b552021-01-27 11:47:00 -05003104static bool is_dead(const Variable& var, const ProgramUsage* usage) {
Brian Osman010ce6a2020-10-19 16:34:10 -04003105 ProgramUsage::VariableCounts counts = usage->get(var);
3106 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07003107 return false;
3108 }
Brian Osmand1f3b972021-03-22 17:03:42 -04003109 // It's not entirely clear what the rules are for eliding interface variables. Generally, it
3110 // causes problems to elide them, even when they're dead.
3111 return !(var.modifiers().fFlags &
3112 (Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag));
Chris Dalton2284aab2019-11-15 11:02:24 -07003113}
3114
John Stilesdbd4e6f2021-02-16 13:29:15 -05003115void SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind, const VarDeclaration& varDecl) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003116 const Variable& var = varDecl.var();
John Stiles0ca2f592021-01-27 10:58:10 -05003117 // 9999 is a sentinel value used in our built-in modules that causes us to ignore these
3118 // declarations, beyond adding them to the symbol table.
3119 constexpr int kBuiltinIgnore = 9999;
3120 if (var.modifiers().fLayout.fBuiltin == kBuiltinIgnore) {
Brian Osmanc0213602020-10-06 14:43:32 -04003121 return;
3122 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003123 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
John Stilesdbd4e6f2021-02-16 13:29:15 -05003124 kind != ProgramKind::kFragment) {
John Stiles270cec22021-02-17 12:59:36 -05003125 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Osmanc0213602020-10-06 14:43:32 -04003126 return;
3127 }
Brian Osman010ce6a2020-10-19 16:34:10 -04003128 if (is_dead(var, fProgram.fUsage.get())) {
Brian Osmanc0213602020-10-06 14:43:32 -04003129 return;
3130 }
John Stiles0de76f72021-01-29 09:19:39 -05003131 SpvStorageClass_ storageClass = get_storage_class(var, SpvStorageClassPrivate);
John Stilese40d1662021-01-29 10:08:50 -05003132 if (storageClass == SpvStorageClassUniform) {
3133 // Top-level uniforms are emitted in writeUniformBuffer.
3134 fTopLevelUniforms.push_back(&varDecl);
3135 return;
3136 }
3137 const Type& type = var.type();
John Stilesd8fc95d2021-01-26 16:22:53 -05003138 Layout layout = var.modifiers().fLayout;
John Stilese40d1662021-01-29 10:08:50 -05003139 if (layout.fSet < 0 && storageClass == SpvStorageClassUniformConstant) {
John Stiles270cec22021-02-17 12:59:36 -05003140 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
Brian Osmanc0213602020-10-06 14:43:32 -04003141 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003142 SpvId id = this->nextId(&type);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003143 fVariableMap[&var] = id;
Brian Osmanc0213602020-10-06 14:43:32 -04003144 SpvId typeId;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003145 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osmanc0213602020-10-06 14:43:32 -04003146 typeId = this->getPointerType(
John Stilesad2d4942020-12-11 16:55:58 -05003147 *Type::MakeArrayType("sk_in", type.componentType(), fSkInCount),
Brian Osmanc0213602020-10-06 14:43:32 -04003148 storageClass);
3149 } else {
3150 typeId = this->getPointerType(type, storageClass);
3151 }
3152 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003153 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003154 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04003155 SkASSERT(!fCurrentBlock);
3156 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003157 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04003158 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
3159 fCurrentBlock = 0;
3160 }
John Stilesd8fc95d2021-01-26 16:22:53 -05003161 this->writeLayout(layout, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003162 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003163 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
3164 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003165 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003166 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
3167 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003168 }
3169}
3170
Brian Osmanc0213602020-10-06 14:43:32 -04003171void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003172 const Variable& var = varDecl.var();
Ethan Nicholas7f015882021-03-23 14:16:52 -04003173 SpvId id = this->nextId(&var.type());
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003174 fVariableMap[&var] = id;
3175 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04003176 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003177 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
3178 if (varDecl.value()) {
3179 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04003180 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003181 }
3182}
3183
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003184void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003185 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04003186 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04003187 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04003188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003189 case Statement::Kind::kBlock:
John Stiles0693fb82021-01-22 18:27:52 -05003190 this->writeBlock(s.as<Block>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003192 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04003193 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003195 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04003196 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003197 break;
Brian Osmanc0213602020-10-06 14:43:32 -04003198 case Statement::Kind::kVarDeclaration:
3199 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003200 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003201 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04003202 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003203 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003204 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04003205 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003206 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003207 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04003208 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003209 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003210 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04003211 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003212 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003213 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07003214 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
3215 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003216 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07003217 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
3218 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003219 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07003220 this->writeInstruction(SpvOpKill, out);
3221 break;
3222 default:
John Stileseada7bc2021-02-02 16:29:32 -05003223 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003224 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003225 }
3226}
3227
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003228void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04003229 for (const std::unique_ptr<Statement>& stmt : b.children()) {
3230 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003231 }
3232}
3233
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003234void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003235 SpvId test = this->writeExpression(*stmt.test(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003236 SpvId ifTrue = this->nextId(nullptr);
3237 SpvId ifFalse = this->nextId(nullptr);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003238 if (stmt.ifFalse()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003239 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003240 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3241 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3242 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003243 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003244 if (fCurrentBlock) {
3245 this->writeInstruction(SpvOpBranch, end, out);
3246 }
3247 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003248 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003249 if (fCurrentBlock) {
3250 this->writeInstruction(SpvOpBranch, end, out);
3251 }
3252 this->writeLabel(end, out);
3253 } else {
3254 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3255 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3256 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003257 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003258 if (fCurrentBlock) {
3259 this->writeInstruction(SpvOpBranch, ifFalse, out);
3260 }
3261 this->writeLabel(ifFalse, out);
3262 }
3263}
3264
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003265void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003266 if (f.initializer()) {
3267 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003268 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003269 SpvId header = this->nextId(nullptr);
3270 SpvId start = this->nextId(nullptr);
3271 SpvId body = this->nextId(nullptr);
3272 SpvId next = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003273 fContinueTarget.push(next);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003274 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003275 fBreakTarget.push(end);
3276 this->writeInstruction(SpvOpBranch, header, out);
3277 this->writeLabel(header, out);
3278 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003279 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003280 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003281 if (f.test()) {
3282 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003283 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003284 } else {
3285 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003286 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003287 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003288 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003289 if (fCurrentBlock) {
3290 this->writeInstruction(SpvOpBranch, next, out);
3291 }
3292 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003293 if (f.next()) {
3294 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003295 }
3296 this->writeInstruction(SpvOpBranch, header, out);
3297 this->writeLabel(end, out);
3298 fBreakTarget.pop();
3299 fContinueTarget.pop();
3300}
3301
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003302void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003303 SpvId header = this->nextId(nullptr);
3304 SpvId start = this->nextId(nullptr);
3305 SpvId next = this->nextId(nullptr);
3306 SpvId continueTarget = this->nextId(nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003307 fContinueTarget.push(continueTarget);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003308 SpvId end = this->nextId(nullptr);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003309 fBreakTarget.push(end);
3310 this->writeInstruction(SpvOpBranch, header, out);
3311 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003312 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003313 this->writeInstruction(SpvOpBranch, start, out);
3314 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003315 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003316 if (fCurrentBlock) {
3317 this->writeInstruction(SpvOpBranch, next, out);
3318 }
3319 this->writeLabel(next, out);
John Stiles68072a42021-04-16 17:25:55 -04003320 this->writeInstruction(SpvOpBranch, continueTarget, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003321 this->writeLabel(continueTarget, out);
John Stiles68072a42021-04-16 17:25:55 -04003322 SpvId test = this->writeExpression(*d.test(), out);
3323 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003324 this->writeLabel(end, out);
3325 fBreakTarget.pop();
3326 fContinueTarget.pop();
3327}
3328
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003329void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003330 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003331 std::vector<SpvId> labels;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003332 SpvId end = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003333 SpvId defaultLabel = end;
3334 fBreakTarget.push(end);
3335 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003336 auto& cases = s.cases();
John Stilesb23a64b2021-03-11 08:27:59 -05003337 for (const std::unique_ptr<Statement>& stmt : cases) {
3338 const SwitchCase& c = stmt->as<SwitchCase>();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003339 SpvId label = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003340 labels.push_back(label);
John Stilesb23a64b2021-03-11 08:27:59 -05003341 if (c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003342 size += 2;
3343 } else {
3344 defaultLabel = label;
3345 }
3346 }
3347 labels.push_back(end);
3348 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3349 this->writeOpCode(SpvOpSwitch, size, out);
3350 this->writeWord(value, out);
3351 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003352 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003353 const SwitchCase& c = cases[i]->as<SwitchCase>();
3354 if (!c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003355 continue;
3356 }
John Stilesb23a64b2021-03-11 08:27:59 -05003357 this->writeWord(c.value()->as<IntLiteral>().value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003358 this->writeWord(labels[i], out);
3359 }
John Stiles2d4f9592020-10-30 10:29:12 -04003360 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003361 const SwitchCase& c = cases[i]->as<SwitchCase>();
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003362 this->writeLabel(labels[i], out);
John Stilesb23a64b2021-03-11 08:27:59 -05003363 this->writeStatement(*c.statement(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003364 if (fCurrentBlock) {
3365 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3366 }
3367 }
3368 this->writeLabel(end, out);
3369 fBreakTarget.pop();
3370}
3371
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003372void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003373 if (r.expression()) {
3374 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003375 out);
3376 } else {
3377 this->writeInstruction(SpvOpReturn, out);
3378 }
3379}
3380
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003381void SPIRVCodeGenerator::writeGeometryShaderExecutionMode(SpvId entryPoint, OutputStream& out) {
John Stiles270cec22021-02-17 12:59:36 -05003382 SkASSERT(fProgram.fConfig->fKind == ProgramKind::kGeometry);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003383 int invocations = 1;
Brian Osman133724c2020-10-28 14:14:39 -04003384 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003385 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003386 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003387 if (m.fFlags & Modifiers::kIn_Flag) {
3388 if (m.fLayout.fInvocations != -1) {
3389 invocations = m.fLayout.fInvocations;
3390 }
3391 SpvId input;
3392 switch (m.fLayout.fPrimitive) {
3393 case Layout::kPoints_Primitive:
3394 input = SpvExecutionModeInputPoints;
3395 break;
3396 case Layout::kLines_Primitive:
3397 input = SpvExecutionModeInputLines;
3398 break;
3399 case Layout::kLinesAdjacency_Primitive:
3400 input = SpvExecutionModeInputLinesAdjacency;
3401 break;
3402 case Layout::kTriangles_Primitive:
3403 input = SpvExecutionModeTriangles;
3404 break;
3405 case Layout::kTrianglesAdjacency_Primitive:
3406 input = SpvExecutionModeInputTrianglesAdjacency;
3407 break;
3408 default:
3409 input = 0;
3410 break;
3411 }
Ethan Nicholas81d15112018-07-13 12:48:50 -04003412 update_sk_in_count(m, &fSkInCount);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003413 if (input) {
3414 this->writeInstruction(SpvOpExecutionMode, entryPoint, input, out);
3415 }
3416 } else if (m.fFlags & Modifiers::kOut_Flag) {
3417 SpvId output;
3418 switch (m.fLayout.fPrimitive) {
3419 case Layout::kPoints_Primitive:
3420 output = SpvExecutionModeOutputPoints;
3421 break;
3422 case Layout::kLineStrip_Primitive:
3423 output = SpvExecutionModeOutputLineStrip;
3424 break;
3425 case Layout::kTriangleStrip_Primitive:
3426 output = SpvExecutionModeOutputTriangleStrip;
3427 break;
3428 default:
3429 output = 0;
3430 break;
3431 }
3432 if (output) {
3433 this->writeInstruction(SpvOpExecutionMode, entryPoint, output, out);
3434 }
3435 if (m.fLayout.fMaxVertices != -1) {
3436 this->writeInstruction(SpvOpExecutionMode, entryPoint,
3437 SpvExecutionModeOutputVertices, m.fLayout.fMaxVertices,
3438 out);
3439 }
3440 }
3441 }
3442 }
3443 this->writeInstruction(SpvOpExecutionMode, entryPoint, SpvExecutionModeInvocations,
3444 invocations, out);
3445}
3446
John Stilese40d1662021-01-29 10:08:50 -05003447// Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
3448static std::shared_ptr<SymbolTable> get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
3449 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
3450}
3451
John Stiles4d6310a2021-01-26 19:58:22 -05003452SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
3453 const FunctionDeclaration& main) {
3454 // Our goal is to synthesize a tiny helper function which looks like this:
3455 // void _entrypoint() { sk_FragColor = main(); }
3456
3457 // Fish a symbol table out of main().
John Stilese40d1662021-01-29 10:08:50 -05003458 std::shared_ptr<SymbolTable> symbolTable = get_top_level_symbol_table(main);
John Stiles4d6310a2021-01-26 19:58:22 -05003459
3460 // Get `sk_FragColor` as a writable reference.
3461 const Symbol* skFragColorSymbol = (*symbolTable)["sk_FragColor"];
3462 SkASSERT(skFragColorSymbol);
3463 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
3464 auto skFragColorRef = std::make_unique<VariableReference>(/*offset=*/-1, &skFragColorVar,
3465 VariableReference::RefKind::kWrite);
3466 // Synthesize a call to the `main()` function.
3467 if (main.returnType() != skFragColorRef->type()) {
3468 fErrors.error(main.fOffset, "SPIR-V does not support returning '" +
3469 main.returnType().description() + "' from main()");
3470 return {};
3471 }
Brian Osman716aeb92021-04-21 13:20:00 -04003472 ExpressionArray args;
3473 if (main.parameters().size() == 1) {
3474 if (main.parameters()[0]->type() != *fContext.fTypes.fFloat2) {
3475 fErrors.error(main.fOffset,
3476 "SPIR-V does not support parameter of type '" +
3477 main.parameters()[0]->type().description() + "' to main()");
3478 return {};
3479 }
3480 auto zero = std::make_unique<FloatLiteral>(
3481 /*offset=*/-1, 0.0f, fContext.fTypes.fFloatLiteral.get());
3482 auto zeros = std::make_unique<ConstructorSplat>(
3483 /*offset=*/-1, *fContext.fTypes.fFloat2, std::move(zero));
3484 args.push_back(std::move(zeros));
3485 }
John Stiles4d6310a2021-01-26 19:58:22 -05003486 auto callMainFn = std::make_unique<FunctionCall>(/*offset=*/-1, &main.returnType(), &main,
Brian Osman716aeb92021-04-21 13:20:00 -04003487 std::move(args));
John Stiles4d6310a2021-01-26 19:58:22 -05003488
3489 // Synthesize `skFragColor = main()` as a BinaryExpression.
3490 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
3491 /*offset=*/-1,
3492 std::move(skFragColorRef),
3493 Token::Kind::TK_EQ,
3494 std::move(callMainFn),
3495 &main.returnType()));
3496
3497 // Function bodies are always wrapped in a Block.
3498 StatementArray entrypointStmts;
3499 entrypointStmts.push_back(std::move(assignmentStmt));
John Stilesbf16b6c2021-03-12 19:24:31 -05003500 auto entrypointBlock = Block::Make(/*offset=*/-1, std::move(entrypointStmts),
3501 symbolTable, /*isScope=*/true);
John Stiles4d6310a2021-01-26 19:58:22 -05003502 // Declare an entrypoint function.
3503 EntrypointAdapter adapter;
3504 adapter.fLayout = {};
3505 adapter.fModifiers = Modifiers{adapter.fLayout, Modifiers::kHasSideEffects_Flag};
3506 adapter.entrypointDecl =
3507 std::make_unique<FunctionDeclaration>(/*offset=*/-1,
3508 &adapter.fModifiers,
3509 "_entrypoint",
3510 /*parameters=*/std::vector<const Variable*>{},
3511 /*returnType=*/fContext.fTypes.fVoid.get(),
3512 /*builtin=*/false);
3513 // Define it.
3514 adapter.entrypointDef =
3515 std::make_unique<FunctionDefinition>(/*offset=*/-1, adapter.entrypointDecl.get(),
3516 /*builtin=*/false,
3517 /*body=*/std::move(entrypointBlock));
3518
3519 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
3520 return adapter;
3521}
3522
John Stilese40d1662021-01-29 10:08:50 -05003523void SPIRVCodeGenerator::writeUniformBuffer(std::shared_ptr<SymbolTable> topLevelSymbolTable) {
3524 SkASSERT(!fTopLevelUniforms.empty());
3525 static constexpr char kUniformBufferName[] = "_UniformBuffer";
3526
3527 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
3528 // a lookup table of variables to UniformBuffer field indices.
3529 std::vector<Type::Field> fields;
3530 fields.reserve(fTopLevelUniforms.size());
3531 fTopLevelUniformMap.reserve(fTopLevelUniforms.size());
3532 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
3533 const Variable* var = &topLevelUniform->var();
3534 fTopLevelUniformMap[var] = (int)fields.size();
3535 fields.emplace_back(var->modifiers(), var->name(), &var->type());
3536 }
3537 fUniformBuffer.fStruct = Type::MakeStructType(/*offset=*/-1, kUniformBufferName,
3538 std::move(fields));
3539
3540 // Create a global variable to contain this struct.
3541 Layout layout;
John Stiles270cec22021-02-17 12:59:36 -05003542 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
3543 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilese40d1662021-01-29 10:08:50 -05003544 Modifiers modifiers{layout, Modifiers::kUniform_Flag};
3545
3546 fUniformBuffer.fInnerVariable = std::make_unique<Variable>(
John Stilesf2872e62021-05-04 11:38:43 -04003547 /*offset=*/-1, fProgram.fModifiers->add(modifiers), kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003548 fUniformBuffer.fStruct.get(), /*builtin=*/false, Variable::Storage::kGlobal);
3549
3550 // Create an interface block object for this global variable.
3551 fUniformBuffer.fInterfaceBlock = std::make_unique<InterfaceBlock>(
3552 /*offset=*/-1, fUniformBuffer.fInnerVariable.get(), kUniformBufferName,
3553 kUniformBufferName, /*arraySize=*/0, topLevelSymbolTable);
3554
3555 // Generate an interface block and hold onto its ID.
3556 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
3557}
3558
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003559void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003560 fGLSLExtendedInstructions = this->nextId(nullptr);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003561 StringStream body;
John Stiles4d6310a2021-01-26 19:58:22 -05003562 // Assign SpvIds to functions.
3563 const FunctionDeclaration* main = nullptr;
Brian Osman133724c2020-10-28 14:14:39 -04003564 for (const ProgramElement* e : program.elements()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003565 if (e->is<FunctionDefinition>()) {
3566 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
3567 const FunctionDeclaration& funcDecl = funcDef.declaration();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003568 fFunctionMap[&funcDecl] = this->nextId(nullptr);
John Stilese8da4d22021-03-24 09:19:45 -04003569 if (funcDecl.isMain()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003570 main = &funcDecl;
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003571 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003572 }
3573 }
John Stiles4d6310a2021-01-26 19:58:22 -05003574 // Make sure we have a main() function.
3575 if (!main) {
3576 fErrors.error(/*offset=*/0, "program does not contain a main() function");
3577 return;
3578 }
3579 // Emit interface blocks.
3580 std::set<SpvId> interfaceVars;
Brian Osman133724c2020-10-28 14:14:39 -04003581 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003582 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003583 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003584 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003585
3586 const Modifiers& modifiers = intf.variable().modifiers();
John Stiles8e2a84b2021-04-19 09:35:38 -04003587 if ((modifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003588 modifiers.fLayout.fBuiltin == -1 &&
Brian Osman010ce6a2020-10-19 16:34:10 -04003589 !is_dead(intf.variable(), fProgram.fUsage.get())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003590 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003591 }
3592 }
3593 }
John Stiles4d6310a2021-01-26 19:58:22 -05003594 // Emit global variable declarations.
Brian Osman133724c2020-10-28 14:14:39 -04003595 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003596 if (e->is<GlobalVarDeclaration>()) {
John Stiles270cec22021-02-17 12:59:36 -05003597 this->writeGlobalVar(program.fConfig->fKind,
John Stilese40d1662021-01-29 10:08:50 -05003598 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07003599 }
3600 }
John Stilese40d1662021-01-29 10:08:50 -05003601 // Emit top-level uniforms into a dedicated uniform buffer.
3602 if (!fTopLevelUniforms.empty()) {
3603 this->writeUniformBuffer(get_top_level_symbol_table(*main));
3604 }
John Stiles4d6310a2021-01-26 19:58:22 -05003605 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
3606 // main() and stores the result into sk_FragColor.
3607 EntrypointAdapter adapter;
3608 if (main->returnType() == *fContext.fTypes.fHalf4) {
3609 adapter = this->writeEntrypointAdapter(*main);
3610 if (adapter.entrypointDecl) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003611 fFunctionMap[adapter.entrypointDecl.get()] = this->nextId(nullptr);
John Stiles4d6310a2021-01-26 19:58:22 -05003612 this->writeFunction(*adapter.entrypointDef, body);
3613 main = adapter.entrypointDecl.get();
3614 }
3615 }
3616 // Emit all the functions.
Brian Osman133724c2020-10-28 14:14:39 -04003617 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003618 if (e->is<FunctionDefinition>()) {
3619 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003620 }
3621 }
John Stiles4d6310a2021-01-26 19:58:22 -05003622 // Add global in/out variables to the list of interface variables.
ethannicholasb3058bd2016-07-01 08:22:01 -07003623 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003624 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003625 if (var->storage() == Variable::Storage::kGlobal &&
John Stiles8e2a84b2021-04-19 09:35:38 -04003626 (var->modifiers().fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
Brian Osman010ce6a2020-10-19 16:34:10 -04003627 !is_dead(*var, fProgram.fUsage.get())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003628 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003629 }
3630 }
3631 this->writeCapabilities(out);
3632 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3633 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003634 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().length() + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003635 (int32_t) interfaceVars.size(), out);
John Stiles270cec22021-02-17 12:59:36 -05003636 switch (program.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05003637 case ProgramKind::kVertex:
ethannicholasb3058bd2016-07-01 08:22:01 -07003638 this->writeWord(SpvExecutionModelVertex, out);
3639 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003640 case ProgramKind::kFragment:
ethannicholasb3058bd2016-07-01 08:22:01 -07003641 this->writeWord(SpvExecutionModelFragment, out);
3642 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003643 case ProgramKind::kGeometry:
Ethan Nicholas52cad152017-02-16 16:37:32 -05003644 this->writeWord(SpvExecutionModelGeometry, out);
3645 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003646 default:
John Stilesf57207b2021-02-02 17:50:34 -05003647 SK_ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003648 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003649 SpvId entryPoint = fFunctionMap[main];
3650 this->writeWord(entryPoint, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003651 this->writeString(main->name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003652 for (int var : interfaceVars) {
3653 this->writeWord(var, out);
3654 }
John Stiles270cec22021-02-17 12:59:36 -05003655 if (program.fConfig->fKind == ProgramKind::kGeometry) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003656 this->writeGeometryShaderExecutionMode(entryPoint, out);
3657 }
John Stiles270cec22021-02-17 12:59:36 -05003658 if (program.fConfig->fKind == ProgramKind::kFragment) {
Greg Daniel64773e62016-11-22 09:44:03 -05003659 this->writeInstruction(SpvOpExecutionMode,
3660 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003661 SpvExecutionModeOriginUpperLeft,
3662 out);
3663 }
Brian Osman133724c2020-10-28 14:14:39 -04003664 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003665 if (e->is<Extension>()) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003666 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003667 }
3668 }
Greg Daniel64773e62016-11-22 09:44:03 -05003669
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003670 write_stringstream(fExtraGlobalsBuffer, out);
3671 write_stringstream(fNameBuffer, out);
3672 write_stringstream(fDecorationBuffer, out);
3673 write_stringstream(fConstantBuffer, out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003674 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003675}
3676
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003677bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04003678 SkASSERT(!fErrors.errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003679 this->writeWord(SpvMagicNumber, *fOut);
3680 this->writeWord(SpvVersion, *fOut);
3681 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003682 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003683 this->writeInstructions(fProgram, buffer);
3684 this->writeWord(fIdCount, *fOut);
3685 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003686 write_stringstream(buffer, *fOut);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003687 return 0 == fErrors.errorCount();
ethannicholasb3058bd2016-07-01 08:22:01 -07003688}
3689
John Stilesa6841be2020-08-06 14:11:56 -04003690} // namespace SkSL