blob: 6863c8096674a8157da2924fdb43bc4870e4c39a [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
Brian Salomond8d85b92021-07-07 09:41:17 -040012#include "include/sksl/DSLCore.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/SkSLCompiler.h"
Brian Osman00185012021-02-04 16:07:11 -050014#include "src/sksl/SkSLOperators.h"
Brian Salomond8d85b92021-07-07 09:41:17 -040015#include "src/sksl/dsl/priv/DSLWriter.h"
John Stiles4d6310a2021-01-26 19:58:22 -050016#include "src/sksl/ir/SkSLBlock.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050017#include "src/sksl/ir/SkSLExpressionStatement.h"
18#include "src/sksl/ir/SkSLExtension.h"
Brian Salomond8d85b92021-07-07 09:41:17 -040019#include "src/sksl/ir/SkSLField.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/sksl/ir/SkSLIndexExpression.h"
21#include "src/sksl/ir/SkSLVariableReference.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070022
Ethan Nicholas0be34802019-08-15 12:36:58 -040023#ifdef SK_VULKAN
24#include "src/gpu/vk/GrVkCaps.h"
25#endif
26
John Stilescd806892021-01-06 13:33:31 -050027#define kLast_Capability SpvCapabilityMultiViewport
28
Brian Salomond8d85b92021-07-07 09:41:17 -040029constexpr int DEVICE_FRAGCOORDS_BUILTIN = -1000;
30constexpr int DEVICE_CLOCKWISE_BUILTIN = -1001;
31
ethannicholasb3058bd2016-07-01 08:22:01 -070032namespace SkSL {
33
ethannicholasb3058bd2016-07-01 08:22:01 -070034static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
35
36void SPIRVCodeGenerator::setupIntrinsics() {
John Stilesaaac4e42021-05-06 14:08:28 -040037#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, GLSLstd450 ## x, \
38 GLSLstd450 ## x, GLSLstd450 ## x, GLSLstd450 ## x)
39#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, \
40 GLSLstd450 ## ifFloat, \
41 GLSLstd450 ## ifInt, \
42 GLSLstd450 ## ifUInt, \
ethannicholasb3058bd2016-07-01 08:22:01 -070043 SpvOpUndef)
John Stilesaaac4e42021-05-06 14:08:28 -040044#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicOpcodeKind, \
45 SpvOp ## x, SpvOp ## x, SpvOp ## x, SpvOp ## x)
46#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicOpcodeKind, k ## x ## _SpecialIntrinsic, \
47 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
ethannicholasb3058bd2016-07-01 08:22:01 -070048 k ## x ## _SpecialIntrinsic)
John Stilesaaac4e42021-05-06 14:08:28 -040049 fIntrinsicMap[k_round_IntrinsicKind] = ALL_GLSL(Round);
50 fIntrinsicMap[k_roundEven_IntrinsicKind] = ALL_GLSL(RoundEven);
51 fIntrinsicMap[k_trunc_IntrinsicKind] = ALL_GLSL(Trunc);
52 fIntrinsicMap[k_abs_IntrinsicKind] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
53 fIntrinsicMap[k_sign_IntrinsicKind] = BY_TYPE_GLSL(FSign, SSign, SSign);
54 fIntrinsicMap[k_floor_IntrinsicKind] = ALL_GLSL(Floor);
55 fIntrinsicMap[k_ceil_IntrinsicKind] = ALL_GLSL(Ceil);
56 fIntrinsicMap[k_fract_IntrinsicKind] = ALL_GLSL(Fract);
57 fIntrinsicMap[k_radians_IntrinsicKind] = ALL_GLSL(Radians);
58 fIntrinsicMap[k_degrees_IntrinsicKind] = ALL_GLSL(Degrees);
59 fIntrinsicMap[k_sin_IntrinsicKind] = ALL_GLSL(Sin);
60 fIntrinsicMap[k_cos_IntrinsicKind] = ALL_GLSL(Cos);
61 fIntrinsicMap[k_tan_IntrinsicKind] = ALL_GLSL(Tan);
62 fIntrinsicMap[k_asin_IntrinsicKind] = ALL_GLSL(Asin);
63 fIntrinsicMap[k_acos_IntrinsicKind] = ALL_GLSL(Acos);
64 fIntrinsicMap[k_atan_IntrinsicKind] = SPECIAL(Atan);
65 fIntrinsicMap[k_sinh_IntrinsicKind] = ALL_GLSL(Sinh);
66 fIntrinsicMap[k_cosh_IntrinsicKind] = ALL_GLSL(Cosh);
67 fIntrinsicMap[k_tanh_IntrinsicKind] = ALL_GLSL(Tanh);
68 fIntrinsicMap[k_asinh_IntrinsicKind] = ALL_GLSL(Asinh);
69 fIntrinsicMap[k_acosh_IntrinsicKind] = ALL_GLSL(Acosh);
70 fIntrinsicMap[k_atanh_IntrinsicKind] = ALL_GLSL(Atanh);
71 fIntrinsicMap[k_pow_IntrinsicKind] = ALL_GLSL(Pow);
72 fIntrinsicMap[k_exp_IntrinsicKind] = ALL_GLSL(Exp);
73 fIntrinsicMap[k_log_IntrinsicKind] = ALL_GLSL(Log);
74 fIntrinsicMap[k_exp2_IntrinsicKind] = ALL_GLSL(Exp2);
75 fIntrinsicMap[k_log2_IntrinsicKind] = ALL_GLSL(Log2);
76 fIntrinsicMap[k_sqrt_IntrinsicKind] = ALL_GLSL(Sqrt);
77 fIntrinsicMap[k_inverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
78 fIntrinsicMap[k_outerProduct_IntrinsicKind] = ALL_SPIRV(OuterProduct);
79 fIntrinsicMap[k_transpose_IntrinsicKind] = ALL_SPIRV(Transpose);
80 fIntrinsicMap[k_isinf_IntrinsicKind] = ALL_SPIRV(IsInf);
81 fIntrinsicMap[k_isnan_IntrinsicKind] = ALL_SPIRV(IsNan);
82 fIntrinsicMap[k_inversesqrt_IntrinsicKind] = ALL_GLSL(InverseSqrt);
83 fIntrinsicMap[k_determinant_IntrinsicKind] = ALL_GLSL(Determinant);
84 fIntrinsicMap[k_matrixCompMult_IntrinsicKind] = SPECIAL(MatrixCompMult);
85 fIntrinsicMap[k_matrixInverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
86 fIntrinsicMap[k_mod_IntrinsicKind] = SPECIAL(Mod);
87 fIntrinsicMap[k_modf_IntrinsicKind] = ALL_GLSL(Modf);
88 fIntrinsicMap[k_min_IntrinsicKind] = SPECIAL(Min);
89 fIntrinsicMap[k_max_IntrinsicKind] = SPECIAL(Max);
90 fIntrinsicMap[k_clamp_IntrinsicKind] = SPECIAL(Clamp);
91 fIntrinsicMap[k_saturate_IntrinsicKind] = SPECIAL(Saturate);
92 fIntrinsicMap[k_dot_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
93 SpvOpDot, SpvOpUndef, SpvOpUndef, SpvOpUndef);
94 fIntrinsicMap[k_mix_IntrinsicKind] = SPECIAL(Mix);
95 fIntrinsicMap[k_step_IntrinsicKind] = SPECIAL(Step);
96 fIntrinsicMap[k_smoothstep_IntrinsicKind] = SPECIAL(SmoothStep);
97 fIntrinsicMap[k_fma_IntrinsicKind] = ALL_GLSL(Fma);
98 fIntrinsicMap[k_frexp_IntrinsicKind] = ALL_GLSL(Frexp);
99 fIntrinsicMap[k_ldexp_IntrinsicKind] = ALL_GLSL(Ldexp);
ethannicholasb3058bd2016-07-01 08:22:01 -0700100
John Stilesaaac4e42021-05-06 14:08:28 -0400101#define PACK(type) fIntrinsicMap[k_pack##type##_IntrinsicKind] = ALL_GLSL(Pack##type); \
102 fIntrinsicMap[k_unpack##type##_IntrinsicKind] = ALL_GLSL(Unpack##type)
ethannicholasb3058bd2016-07-01 08:22:01 -0700103 PACK(Snorm4x8);
104 PACK(Unorm4x8);
105 PACK(Snorm2x16);
106 PACK(Unorm2x16);
107 PACK(Half2x16);
108 PACK(Double2x32);
John Stilesaaac4e42021-05-06 14:08:28 -0400109#undef PACK
110 fIntrinsicMap[k_length_IntrinsicKind] = ALL_GLSL(Length);
111 fIntrinsicMap[k_distance_IntrinsicKind] = ALL_GLSL(Distance);
112 fIntrinsicMap[k_cross_IntrinsicKind] = ALL_GLSL(Cross);
113 fIntrinsicMap[k_normalize_IntrinsicKind] = ALL_GLSL(Normalize);
114 fIntrinsicMap[k_faceforward_IntrinsicKind] = ALL_GLSL(FaceForward);
115 fIntrinsicMap[k_reflect_IntrinsicKind] = ALL_GLSL(Reflect);
116 fIntrinsicMap[k_refract_IntrinsicKind] = ALL_GLSL(Refract);
117 fIntrinsicMap[k_bitCount_IntrinsicKind] = ALL_SPIRV(BitCount);
118 fIntrinsicMap[k_findLSB_IntrinsicKind] = ALL_GLSL(FindILsb);
119 fIntrinsicMap[k_findMSB_IntrinsicKind] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
120 fIntrinsicMap[k_dFdx_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
121 SpvOpDPdx, SpvOpUndef,
122 SpvOpUndef, SpvOpUndef);
123 fIntrinsicMap[k_dFdy_IntrinsicKind] = SPECIAL(DFdy);
124 fIntrinsicMap[k_fwidth_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
125 SpvOpFwidth, SpvOpUndef,
126 SpvOpUndef, SpvOpUndef);
127 fIntrinsicMap[k_makeSampler2D_IntrinsicKind] = SPECIAL(SampledImage);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400128
John Stilesaaac4e42021-05-06 14:08:28 -0400129 fIntrinsicMap[k_sample_IntrinsicKind] = SPECIAL(Texture);
130 fIntrinsicMap[k_subpassLoad_IntrinsicKind] = SPECIAL(SubpassLoad);
Greg Daniel64773e62016-11-22 09:44:03 -0500131
John Stilesaaac4e42021-05-06 14:08:28 -0400132 fIntrinsicMap[k_floatBitsToInt_IntrinsicKind] = ALL_SPIRV(Bitcast);
133 fIntrinsicMap[k_floatBitsToUint_IntrinsicKind] = ALL_SPIRV(Bitcast);
134 fIntrinsicMap[k_intBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
135 fIntrinsicMap[k_uintBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
John Stilescc9ff002020-12-09 18:39:41 -0500136
John Stilesaaac4e42021-05-06 14:08:28 -0400137 fIntrinsicMap[k_any_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Brian Osman540c13a2020-11-24 16:55:34 -0500138 SpvOpUndef, SpvOpUndef,
John Stilesaaac4e42021-05-06 14:08:28 -0400139 SpvOpUndef, SpvOpAny);
140 fIntrinsicMap[k_all_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
141 SpvOpUndef, SpvOpUndef,
142 SpvOpUndef, SpvOpAll);
143 fIntrinsicMap[k_not_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
144 SpvOpUndef, SpvOpUndef, SpvOpUndef,
Brian Osman540c13a2020-11-24 16:55:34 -0500145 SpvOpLogicalNot);
John Stilesaaac4e42021-05-06 14:08:28 -0400146 fIntrinsicMap[k_equal_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400147 SpvOpFOrdEqual, SpvOpIEqual,
148 SpvOpIEqual, SpvOpLogicalEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400149 fIntrinsicMap[k_notEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400150 SpvOpFOrdNotEqual, SpvOpINotEqual,
151 SpvOpINotEqual,
152 SpvOpLogicalNotEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400153 fIntrinsicMap[k_lessThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
154 SpvOpFOrdLessThan,
155 SpvOpSLessThan,
156 SpvOpULessThan,
157 SpvOpUndef);
158 fIntrinsicMap[k_lessThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
159 SpvOpFOrdLessThanEqual,
160 SpvOpSLessThanEqual,
161 SpvOpULessThanEqual,
162 SpvOpUndef);
163 fIntrinsicMap[k_greaterThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
164 SpvOpFOrdGreaterThan,
165 SpvOpSGreaterThan,
166 SpvOpUGreaterThan,
167 SpvOpUndef);
168 fIntrinsicMap[k_greaterThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
169 SpvOpFOrdGreaterThanEqual,
170 SpvOpSGreaterThanEqual,
171 SpvOpUGreaterThanEqual,
172 SpvOpUndef);
173 fIntrinsicMap[k_EmitVertex_IntrinsicKind] = ALL_SPIRV(EmitVertex);
174 fIntrinsicMap[k_EndPrimitive_IntrinsicKind] = ALL_SPIRV(EndPrimitive);
ethannicholasb3058bd2016-07-01 08:22:01 -0700175// interpolateAt* not yet supported...
176}
177
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400178void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700179 out.write((const char*) &word, sizeof(word));
ethannicholasb3058bd2016-07-01 08:22:01 -0700180}
181
ethannicholasd598f792016-07-25 10:08:54 -0700182static bool is_float(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500183 return (type.isScalar() || type.isVector() || type.isMatrix()) &&
184 type.componentType().isFloat();
ethannicholasb3058bd2016-07-01 08:22:01 -0700185}
186
ethannicholasd598f792016-07-25 10:08:54 -0700187static bool is_signed(const Context& context, const Type& type) {
Brian Osmanc9145f32021-07-08 13:40:10 -0400188 return (type.isScalar() || type.isVector()) && type.componentType().isSigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700189}
190
ethannicholasd598f792016-07-25 10:08:54 -0700191static bool is_unsigned(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500192 return (type.isScalar() || type.isVector()) && type.componentType().isUnsigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700193}
194
ethannicholasd598f792016-07-25 10:08:54 -0700195static bool is_bool(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500196 return (type.isScalar() || type.isVector()) && type.componentType().isBoolean();
ethannicholasb3058bd2016-07-01 08:22:01 -0700197}
198
ethannicholasd598f792016-07-25 10:08:54 -0700199static bool is_out(const Variable& var) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -0400200 return (var.modifiers().fFlags & Modifiers::kOut_Flag) != 0;
ethannicholasb3058bd2016-07-01 08:22:01 -0700201}
202
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400203void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400204 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
205 SkASSERT(opCode != SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700206 switch (opCode) {
207 case SpvOpReturn: // fall through
208 case SpvOpReturnValue: // fall through
ethannicholas552882f2016-07-07 06:30:48 -0700209 case SpvOpKill: // fall through
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500210 case SpvOpSwitch: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700211 case SpvOpBranch: // fall through
212 case SpvOpBranchConditional:
John Stilesf2b08cc2021-05-17 14:46:05 -0400213 if (fCurrentBlock == 0) {
214 // We just encountered dead code--instructions that don't have an associated block.
215 // Synthesize a label if this happens; this is necessary to satisfy the validator.
216 this->writeLabel(this->nextId(nullptr), out);
217 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700218 fCurrentBlock = 0;
219 break;
220 case SpvOpConstant: // fall through
221 case SpvOpConstantTrue: // fall through
222 case SpvOpConstantFalse: // fall through
223 case SpvOpConstantComposite: // fall through
224 case SpvOpTypeVoid: // fall through
225 case SpvOpTypeInt: // fall through
226 case SpvOpTypeFloat: // fall through
227 case SpvOpTypeBool: // fall through
228 case SpvOpTypeVector: // fall through
229 case SpvOpTypeMatrix: // fall through
230 case SpvOpTypeArray: // fall through
231 case SpvOpTypePointer: // fall through
232 case SpvOpTypeFunction: // fall through
233 case SpvOpTypeRuntimeArray: // fall through
234 case SpvOpTypeStruct: // fall through
235 case SpvOpTypeImage: // fall through
236 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400237 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700238 case SpvOpVariable: // fall through
239 case SpvOpFunction: // fall through
240 case SpvOpFunctionParameter: // fall through
241 case SpvOpFunctionEnd: // fall through
242 case SpvOpExecutionMode: // fall through
243 case SpvOpMemoryModel: // fall through
244 case SpvOpCapability: // fall through
245 case SpvOpExtInstImport: // fall through
246 case SpvOpEntryPoint: // fall through
247 case SpvOpSource: // fall through
248 case SpvOpSourceExtension: // fall through
249 case SpvOpName: // fall through
250 case SpvOpMemberName: // fall through
251 case SpvOpDecorate: // fall through
252 case SpvOpMemberDecorate:
253 break;
254 default:
John Stilesf3a28db2021-03-10 23:00:47 -0500255 // We may find ourselves with dead code--instructions that don't have an associated
256 // block. This should be a rare event, but if it happens, synthesize a label; this is
257 // necessary to satisfy the validator.
258 if (fCurrentBlock == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400259 this->writeLabel(this->nextId(nullptr), out);
John Stiles7142e402021-02-23 12:28:18 -0500260 }
John Stiles453f1432021-02-25 16:58:04 -0500261 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700262 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700263 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700264}
265
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400266void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500267 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700268 fCurrentBlock = label;
269 this->writeInstruction(SpvOpLabel, label, out);
270}
271
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400272void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700273 this->writeOpCode(opCode, 1, out);
274}
275
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400276void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700277 this->writeOpCode(opCode, 2, out);
278 this->writeWord(word1, out);
279}
280
Ethan Nicholas962dec42021-06-10 13:06:39 -0400281void SPIRVCodeGenerator::writeString(skstd::string_view s, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400282 out.write(s.data(), s.length());
283 switch (s.length() % 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700284 case 1:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500285 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400286 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700287 case 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500288 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400289 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700290 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500291 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700292 break;
293 default:
294 this->writeWord(0, out);
295 }
296}
297
Ethan Nicholas962dec42021-06-10 13:06:39 -0400298void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, skstd::string_view string,
299 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400300 this->writeOpCode(opCode, 1 + (string.length() + 4) / 4, out);
301 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700302}
303
304
Ethan Nicholas962dec42021-06-10 13:06:39 -0400305void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, skstd::string_view string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400306 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400307 this->writeOpCode(opCode, 2 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700308 this->writeWord(word1, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400309 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700310}
311
Greg Daniel64773e62016-11-22 09:44:03 -0500312void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400313 skstd::string_view string, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400314 this->writeOpCode(opCode, 3 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700315 this->writeWord(word1, out);
316 this->writeWord(word2, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400317 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700318}
319
Greg Daniel64773e62016-11-22 09:44:03 -0500320void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400321 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700322 this->writeOpCode(opCode, 3, out);
323 this->writeWord(word1, out);
324 this->writeWord(word2, out);
325}
326
Greg Daniel64773e62016-11-22 09:44:03 -0500327void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400328 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700329 this->writeOpCode(opCode, 4, out);
330 this->writeWord(word1, out);
331 this->writeWord(word2, out);
332 this->writeWord(word3, out);
333}
334
Greg Daniel64773e62016-11-22 09:44:03 -0500335void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400336 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700337 this->writeOpCode(opCode, 5, out);
338 this->writeWord(word1, out);
339 this->writeWord(word2, out);
340 this->writeWord(word3, out);
341 this->writeWord(word4, out);
342}
343
Greg Daniel64773e62016-11-22 09:44:03 -0500344void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
345 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400346 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700347 this->writeOpCode(opCode, 6, out);
348 this->writeWord(word1, out);
349 this->writeWord(word2, out);
350 this->writeWord(word3, out);
351 this->writeWord(word4, out);
352 this->writeWord(word5, out);
353}
354
Greg Daniel64773e62016-11-22 09:44:03 -0500355void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700356 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400357 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700358 this->writeOpCode(opCode, 7, out);
359 this->writeWord(word1, out);
360 this->writeWord(word2, out);
361 this->writeWord(word3, out);
362 this->writeWord(word4, out);
363 this->writeWord(word5, out);
364 this->writeWord(word6, out);
365}
366
Greg Daniel64773e62016-11-22 09:44:03 -0500367void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700368 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400369 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700370 this->writeOpCode(opCode, 8, out);
371 this->writeWord(word1, out);
372 this->writeWord(word2, out);
373 this->writeWord(word3, out);
374 this->writeWord(word4, out);
375 this->writeWord(word5, out);
376 this->writeWord(word6, out);
377 this->writeWord(word7, out);
378}
379
Greg Daniel64773e62016-11-22 09:44:03 -0500380void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700381 int32_t word3, int32_t word4, int32_t word5,
382 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400383 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700384 this->writeOpCode(opCode, 9, out);
385 this->writeWord(word1, out);
386 this->writeWord(word2, out);
387 this->writeWord(word3, out);
388 this->writeWord(word4, out);
389 this->writeWord(word5, out);
390 this->writeWord(word6, out);
391 this->writeWord(word7, out);
392 this->writeWord(word8, out);
393}
394
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400395void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700396 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
397 if (fCapabilities & bit) {
398 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
399 }
400 }
John Stiles270cec22021-02-17 12:59:36 -0500401 if (fProgram.fConfig->fKind == ProgramKind::kGeometry) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400402 this->writeInstruction(SpvOpCapability, SpvCapabilityGeometry, out);
403 }
Ethan Nicholas81d15112018-07-13 12:48:50 -0400404 else {
405 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
406 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700407}
408
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400409SpvId SPIRVCodeGenerator::nextId(const Type* type) {
410 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
411 ? Precision::kRelaxed
412 : Precision::kDefault);
413}
414
415SpvId SPIRVCodeGenerator::nextId(Precision precision) {
416 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
417 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
418 fDecorationBuffer);
419 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700420 return fIdCount++;
421}
422
Ethan Nicholas19671772016-11-28 16:30:17 -0500423void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
424 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400425 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700426 // go ahead and write all of the field types, so we don't inadvertently write them while we're
427 // in the middle of writing the struct instruction
428 std::vector<SpvId> types;
429 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500430 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700431 }
432 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
433 this->writeWord(resultId, fConstantBuffer);
434 for (SpvId id : types) {
435 this->writeWord(id, fConstantBuffer);
436 }
437 size_t offset = 0;
438 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400439 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500440 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
John Stiles0023c0c2020-11-16 13:32:18 -0500441 fErrors.error(type.fOffset, "type '" + field.fType->name() + "' is not permitted here");
442 return;
443 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400444 size_t size = memoryLayout.size(*field.fType);
445 size_t alignment = memoryLayout.alignment(*field.fType);
446 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500447 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500448 if (fieldLayout.fOffset < (int) offset) {
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 at "
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500451 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500452 }
453 if (fieldLayout.fOffset % alignment) {
Ethan Nicholas5b5f0962017-09-11 13:50:14 -0700454 fErrors.error(type.fOffset,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400455 "offset of field '" + field.fName + "' must be a multiple"
Ethan Nicholas941e7e22016-12-12 15:33:30 -0500456 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500457 }
458 offset = fieldLayout.fOffset;
459 } else {
460 size_t mod = offset % alignment;
461 if (mod) {
462 offset += alignment - mod;
463 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700464 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400465 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500466 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400467 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500468 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700469 (SpvId) offset, fDecorationBuffer);
470 }
John Stiles9aeed132020-11-24 17:36:06 -0500471 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500472 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700473 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500474 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400475 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800476 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700477 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400478 if (!field.fType->highPrecision()) {
479 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
480 SpvDecorationRelaxedPrecision, fDecorationBuffer);
481 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700482 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500483 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700484 offset += alignment - offset % alignment;
485 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700486 }
487}
488
Ethan Nicholase2c49992020-10-05 11:49:11 -0400489const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500490 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500491 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400492 }
Brian Osmanc9145f32021-07-08 13:40:10 -0400493 if (type.isSigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500494 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400495 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500496 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500497 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400498 }
John Stiles9aeed132020-11-24 17:36:06 -0500499 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500500 if (type.componentType() == *fContext.fTypes.fHalf) {
501 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400502 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400503 if (type.componentType() == *fContext.fTypes.fShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500504 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400505 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400506 if (type.componentType() == *fContext.fTypes.fUShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500507 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400508 }
509 }
510 return type;
511}
512
ethannicholasb3058bd2016-07-01 08:22:01 -0700513SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800514 return this->getType(type, fDefaultLayout);
515}
516
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400517SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400518 const Type& type = this->getActualType(rawType);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400519 String key(type.name());
John Stilesc0c51062020-12-03 17:16:29 -0500520 if (type.isStruct() || type.isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400521 key += to_string((int)layout.fStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500522#ifdef SK_DEBUG
523 SkASSERT(layout.fStd == MemoryLayout::Standard::k140_Standard ||
524 layout.fStd == MemoryLayout::Standard::k430_Standard);
525 MemoryLayout::Standard otherStd = layout.fStd == MemoryLayout::Standard::k140_Standard
526 ? MemoryLayout::Standard::k430_Standard
527 : MemoryLayout::Standard::k140_Standard;
528 String otherKey = type.name() + to_string((int)otherStd);
529 SkASSERT(fTypeMap.find(otherKey) == fTypeMap.end());
530#endif
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400531 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800532 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700533 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400534 SpvId result = this->nextId(nullptr);
Ethan Nicholase6592142020-09-08 10:22:09 -0400535 switch (type.typeKind()) {
536 case Type::TypeKind::kScalar:
John Stiles4a7dc462020-11-25 11:08:08 -0500537 if (type.isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700538 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500539 } else if (type == *fContext.fTypes.fInt || type == *fContext.fTypes.fShort ||
540 type == *fContext.fTypes.fIntLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700541 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500542 } else if (type == *fContext.fTypes.fUInt || type == *fContext.fTypes.fUShort) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700543 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles54e7c052021-01-11 14:22:36 -0500544 } else if (type == *fContext.fTypes.fFloat || type == *fContext.fTypes.fHalf ||
545 type == *fContext.fTypes.fFloatLiteral) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700546 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700547 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400548 SkASSERT(false);
ethannicholasb3058bd2016-07-01 08:22:01 -0700549 }
550 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400551 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500552 this->writeInstruction(SpvOpTypeVector, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800553 this->getType(type.componentType(), layout),
ethannicholasb3058bd2016-07-01 08:22:01 -0700554 type.columns(), fConstantBuffer);
555 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400556 case Type::TypeKind::kMatrix:
John Stiles51d33982021-03-08 09:18:07 -0500557 this->writeInstruction(
558 SpvOpTypeMatrix,
559 result,
560 this->getType(IndexExpression::IndexType(fContext, type), layout),
561 type.columns(),
562 fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700563 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400564 case Type::TypeKind::kStruct:
ethannicholas8ac838d2016-11-22 08:39:36 -0800565 this->writeStruct(type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700566 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400567 case Type::TypeKind::kArray: {
John Stiles21f5f452020-11-30 09:57:59 -0500568 if (!MemoryLayout::LayoutIsSupported(type)) {
569 fErrors.error(type.fOffset, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400570 return this->nextId(nullptr);
John Stiles21f5f452020-11-30 09:57:59 -0500571 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700572 if (type.columns() > 0) {
John Stilesb5db4822021-01-21 13:04:40 -0500573 SpvId typeId = this->getType(type.componentType(), layout);
John Stiles9ce80f72021-03-11 22:35:19 -0500574 IntLiteral countLiteral(/*offset=*/-1, type.columns(),
575 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -0500576 SpvId countId = this->writeIntLiteral(countLiteral);
577 this->writeInstruction(SpvOpTypeArray, result, typeId, countId,
578 fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500579 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400580 (int32_t) layout.stride(type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800581 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700582 } else {
John Stiles5570c512020-11-19 17:58:07 -0500583 // We shouldn't have any runtime-sized arrays right now
584 fErrors.error(type.fOffset, "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500585 this->writeInstruction(SpvOpTypeRuntimeArray, result,
ethannicholas8ac838d2016-11-22 08:39:36 -0800586 this->getType(type.componentType(), layout),
587 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400588 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
589 (int32_t) layout.stride(type),
590 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700591 }
592 break;
593 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400594 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500595 SpvId image = result;
596 if (SpvDimSubpassData != type.dimensions()) {
Stephen White792e2302019-08-09 13:33:51 -0400597 image = this->getType(type.textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500598 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400599 if (SpvDimBuffer == type.dimensions()) {
600 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
601 }
Greg Daniel64773e62016-11-22 09:44:03 -0500602 if (SpvDimSubpassData != type.dimensions()) {
603 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
604 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700605 break;
606 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400607 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400608 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
609 break;
610 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400611 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400612 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500613 this->getType(*fContext.fTypes.fFloat, layout),
John Stilesc0c51062020-12-03 17:16:29 -0500614 type.dimensions(), type.isDepth(), type.isArrayedTexture(),
Stephen White792e2302019-08-09 13:33:51 -0400615 type.isMultisampled(), type.isSampled() ? 1 : 2,
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400616 SpvImageFormatUnknown, fConstantBuffer);
617 fImageTypeMap[key] = result;
618 break;
619 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700620 default:
John Stiles2558c462021-03-16 17:49:20 -0400621 if (type.isVoid()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700622 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
623 } else {
John Stileseada7bc2021-02-02 16:29:32 -0500624 SkDEBUGFAILF("invalid type: %s", type.description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700625 }
626 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800627 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700628 return result;
629 }
630 return entry->second;
631}
632
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400633SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400634 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400635 this->getType(type);
636 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400637 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400638 return fImageTypeMap[key];
639}
640
ethannicholasd598f792016-07-25 10:08:54 -0700641SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400642 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400643 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400644 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400645 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700646 key += separator;
647 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400648 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700649 }
650 key += ")";
651 auto entry = fTypeMap.find(key);
652 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400653 SpvId result = this->nextId(nullptr);
Ethan Nicholased84b732020-10-08 11:45:44 -0400654 int32_t length = 3 + (int32_t) parameters.size();
655 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700656 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400657 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500658 // glslang seems to treat all function arguments as pointers whether they need to be or
659 // not. I was initially puzzled by this until I ran bizarre failures with certain
660 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700661 // failure case:
662 //
663 // void sphere(float x) {
664 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500665 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700666 // void map() {
667 // sphere(1.0);
668 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500669 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700670 // void main() {
671 // for (int i = 0; i < 1; i++) {
672 // map();
673 // }
674 // }
675 //
Greg Daniel64773e62016-11-22 09:44:03 -0500676 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
677 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700678 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
679 // the spec makes this make sense.
680// if (is_out(function->fParameters[i])) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400681 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
ethannicholasb3058bd2016-07-01 08:22:01 -0700682 SpvStorageClassFunction));
683// } else {
ethannicholasd598f792016-07-25 10:08:54 -0700684// parameterTypes.push_back(this->getType(function.fParameters[i]->fType));
ethannicholasb3058bd2016-07-01 08:22:01 -0700685// }
686 }
687 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
688 this->writeWord(result, fConstantBuffer);
689 this->writeWord(returnType, fConstantBuffer);
690 for (SpvId id : parameterTypes) {
691 this->writeWord(id, fConstantBuffer);
692 }
693 fTypeMap[key] = result;
694 return result;
695 }
696 return entry->second;
697}
698
ethannicholas8ac838d2016-11-22 08:39:36 -0800699SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
700 return this->getPointerType(type, fDefaultLayout, storageClass);
701}
702
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400703SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700704 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400705 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500706 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700707 auto entry = fTypeMap.find(key);
708 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400709 SpvId result = this->nextId(nullptr);
Greg Daniel64773e62016-11-22 09:44:03 -0500710 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700711 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700712 fTypeMap[key] = result;
713 return result;
714 }
715 return entry->second;
716}
717
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400718SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400719 switch (expr.kind()) {
720 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400721 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400722 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400723 return this->writeBoolLiteral(expr.as<BoolLiteral>());
John Stiles7384b372021-04-01 13:48:15 -0400724 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400725 case Expression::Kind::kConstructorStruct:
726 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
John Stilese1182782021-03-30 22:09:37 -0400727 case Expression::Kind::kConstructorDiagonalMatrix:
728 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
John Stiles5abb9e12021-04-06 13:47:19 -0400729 case Expression::Kind::kConstructorMatrixResize:
730 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
John Stilesfd7252f2021-04-04 22:24:40 -0400731 case Expression::Kind::kConstructorScalarCast:
732 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
John Stiles2938eea2021-04-01 18:58:25 -0400733 case Expression::Kind::kConstructorSplat:
734 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
John Stiles8cad6372021-04-07 12:31:13 -0400735 case Expression::Kind::kConstructorCompound:
736 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
737 case Expression::Kind::kConstructorCompoundCast:
738 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400739 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400740 return this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400741 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400742 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400743 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400744 return this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400745 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400746 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400747 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400748 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400749 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400750 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400751 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400752 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400753 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400754 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400755 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400756 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400757 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400758 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700759 default:
John Stileseada7bc2021-02-02 16:29:32 -0500760 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500761 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700762 }
763 return -1;
764}
765
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400766SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400767 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -0400768 auto intrinsic = fIntrinsicMap.find(function.intrinsicKind());
John Stiles93e661a2020-12-08 16:17:00 -0500769 if (intrinsic == fIntrinsicMap.end()) {
770 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
771 return -1;
772 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700773 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500774 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400775 if (arguments.size() > 0) {
776 const Type& type = arguments[0]->type();
John Stilesaaac4e42021-05-06 14:08:28 -0400777 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicOpcodeKind ||
778 is_float(fContext, type)) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400779 intrinsicId = std::get<1>(intrinsic->second);
780 } else if (is_signed(fContext, type)) {
781 intrinsicId = std::get<2>(intrinsic->second);
782 } else if (is_unsigned(fContext, type)) {
783 intrinsicId = std::get<3>(intrinsic->second);
784 } else if (is_bool(fContext, type)) {
785 intrinsicId = std::get<4>(intrinsic->second);
786 } else {
787 intrinsicId = std::get<1>(intrinsic->second);
788 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700789 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400790 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700791 }
792 switch (std::get<0>(intrinsic->second)) {
John Stilesaaac4e42021-05-06 14:08:28 -0400793 case kGLSL_STD_450_IntrinsicOpcodeKind: {
Ethan Nicholas7f015882021-03-23 14:16:52 -0400794 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400795 std::vector<SpvId> argumentIds;
796 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400797 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500798 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400799 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400800 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400801 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400802 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700803 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400804 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400805 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700806 this->writeWord(result, out);
807 this->writeWord(fGLSLExtendedInstructions, out);
808 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400809 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700810 this->writeWord(id, out);
811 }
812 return result;
813 }
John Stilesaaac4e42021-05-06 14:08:28 -0400814 case kSPIRV_IntrinsicOpcodeKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500815 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500816 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500817 intrinsicId = SpvOpFMul;
818 }
Ethan Nicholas7f015882021-03-23 14:16:52 -0400819 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400820 std::vector<SpvId> argumentIds;
821 for (size_t i = 0; i < arguments.size(); i++) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400822 if (function.parameters()[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesec241542021-02-11 17:50:09 -0500823 // TODO(skia:11052): swizzled lvalues won't work with getPointer()
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400824 argumentIds.push_back(this->getLValue(*arguments[i], out)->getPointer());
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400825 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400826 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400827 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700828 }
John Stiles2558c462021-03-16 17:49:20 -0400829 if (!c.type().isVoid()) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400830 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400831 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400832 this->writeWord(result, out);
833 } else {
834 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
835 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400836 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700837 this->writeWord(id, out);
838 }
839 return result;
840 }
John Stilesaaac4e42021-05-06 14:08:28 -0400841 case kSpecial_IntrinsicOpcodeKind:
ethannicholasb3058bd2016-07-01 08:22:01 -0700842 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
843 default:
John Stiles93e661a2020-12-08 16:17:00 -0500844 fErrors.error(c.fOffset, "unsupported intrinsic '" + function.description() + "'");
845 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700846 }
847}
848
Brian Salomond8d85b92021-07-07 09:41:17 -0400849SpvId SPIRVCodeGenerator::vectorize(const Expression& arg, int vectorSize, OutputStream& out) {
850 SkASSERT(vectorSize >= 1 && vectorSize <= 4);
851 const Type& argType = arg.type();
852 SpvId raw = this->writeExpression(arg, out);
853 if (argType.isScalar()) {
854 if (vectorSize == 1) {
855 return raw;
856 }
857 SpvId vector = this->nextId(&argType);
858 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
859 this->writeWord(this->getType(argType.toCompound(fContext, vectorSize, 1)), out);
860 this->writeWord(vector, out);
861 for (int i = 0; i < vectorSize; i++) {
862 this->writeWord(raw, out);
863 }
864 return vector;
865 } else {
866 SkASSERT(vectorSize == argType.columns());
867 return raw;
868 }
869}
870
John Stiles8e3b6be2020-10-13 11:14:08 -0400871std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400872 int vectorSize = 1;
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500873 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500874 if (a->type().isVector()) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400875 if (vectorSize > 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400876 SkASSERT(a->type().columns() == vectorSize);
Brian Salomond8d85b92021-07-07 09:41:17 -0400877 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400878 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500879 }
880 }
881 }
882 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400883 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400884 for (const auto& arg : args) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400885 result.push_back(this->vectorize(*arg, vectorSize, out));
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500886 }
887 return result;
888}
889
890void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
891 SpvId signedInst, SpvId unsignedInst,
892 const std::vector<SpvId>& args,
893 OutputStream& out) {
894 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
895 this->writeWord(this->getType(type), out);
896 this->writeWord(id, out);
897 this->writeWord(fGLSLExtendedInstructions, out);
898
899 if (is_float(fContext, type)) {
900 this->writeWord(floatInst, out);
901 } else if (is_signed(fContext, type)) {
902 this->writeWord(signedInst, out);
903 } else if (is_unsigned(fContext, type)) {
904 this->writeWord(unsignedInst, out);
905 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400906 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500907 }
908 for (SpvId a : args) {
909 this->writeWord(a, out);
910 }
911}
912
Greg Daniel64773e62016-11-22 09:44:03 -0500913SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400914 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400915 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400916 const Type& callType = c.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400917 SpvId result = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700918 switch (kind) {
919 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400920 std::vector<SpvId> argumentIds;
921 for (const std::unique_ptr<Expression>& arg : arguments) {
922 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700923 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400924 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400925 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700926 this->writeWord(result, out);
927 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400928 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
929 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700930 this->writeWord(id, out);
931 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400932 break;
933 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400934 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400935 SkASSERT(arguments.size() == 2);
936 SpvId img = this->writeExpression(*arguments[0], out);
937 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400938 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400939 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400940 result,
941 img,
942 sampler,
943 out);
944 break;
945 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400946 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400947 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400948 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400949 args.reserve_back(2);
John Stiles9ce80f72021-03-11 22:35:19 -0500950 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
951 args.push_back(IntLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
John Stiles8cad6372021-04-07 12:31:13 -0400952 ConstructorCompound ctor(/*offset=*/-1, *fContext.fTypes.fInt2, std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400953 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400954 if (arguments.size() == 1) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400955 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400956 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400957 result,
958 img,
959 coords,
960 out);
961 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400962 SkASSERT(arguments.size() == 2);
963 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400964 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400965 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400966 result,
967 img,
968 coords,
969 SpvImageOperandsSampleMask,
970 sample,
971 out);
972 }
973 break;
974 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700975 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500976 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400977 const Type& arg1Type = arguments[1]->type();
978 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500979 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -0500980 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500981 op = SpvOpImageSampleProjImplicitLod;
982 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500983 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500984 }
985 break;
986 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -0500987 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500988 op = SpvOpImageSampleProjImplicitLod;
989 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500990 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500991 }
992 break;
993 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -0500994 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500995 op = SpvOpImageSampleProjImplicitLod;
996 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500997 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -0500998 }
999 break;
1000 case SpvDimCube: // fall through
1001 case SpvDimRect: // fall through
1002 case SpvDimBuffer: // fall through
1003 case SpvDimSubpassData:
1004 break;
1005 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001006 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001007 SpvId sampler = this->writeExpression(*arguments[0], out);
1008 SpvId uv = this->writeExpression(*arguments[1], out);
1009 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001010 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -07001011 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001012 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -07001013 out);
1014 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001015 SkASSERT(arguments.size() == 2);
John Stiles270cec22021-02-17 12:59:36 -05001016 if (fProgram.fConfig->fSettings.fSharpenTextures) {
John Stiles9ce80f72021-03-11 22:35:19 -05001017 FloatLiteral lodBias(/*offset=*/-1, /*value=*/-0.5,
1018 fContext.fTypes.fFloat.get());
Brian Osman8a83ca42018-02-12 14:32:17 -05001019 this->writeInstruction(op, type, result, sampler, uv,
1020 SpvImageOperandsBiasMask,
1021 this->writeFloatLiteral(lodBias),
1022 out);
1023 } else {
1024 this->writeInstruction(op, type, result, sampler, uv,
1025 out);
1026 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001027 }
1028 break;
1029 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001030 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001031 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001032 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001033 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001034 SpvOp_ op;
1035 if (is_float(fContext, operandType)) {
1036 op = SpvOpFMod;
1037 } else if (is_signed(fContext, operandType)) {
1038 op = SpvOpSMod;
1039 } else if (is_unsigned(fContext, operandType)) {
1040 op = SpvOpUMod;
1041 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001042 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001043 return 0;
1044 }
1045 this->writeOpCode(op, 5, out);
1046 this->writeWord(this->getType(operandType), out);
1047 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001048 this->writeWord(args[0], out);
1049 this->writeWord(args[1], out);
1050 break;
1051 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001052 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001053 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001054 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001055 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001056 this->writeWord(result, out);
1057 this->writeWord(fn, out);
Brian Salomond8d85b92021-07-07 09:41:17 -04001058 this->addRTFlipUniform(c.fOffset);
1059 using namespace dsl;
1060 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
1061 SKSL_RTFLIP_NAME));
1062 SpvId rtFlipY = this->vectorize(*rtFlip.y().release(), callType.columns(), out);
1063 SpvId flipped = this->nextId(&callType);
1064 this->writeInstruction(SpvOpFMul, this->getType(callType), flipped, result, rtFlipY,
1065 out);
1066 result = flipped;
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001067 break;
1068 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001069 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001070 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001071 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001072 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001073 GLSLstd450UClamp, args, out);
1074 break;
1075 }
1076 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001077 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001078 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001079 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001080 GLSLstd450UMax, args, out);
1081 break;
1082 }
1083 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001084 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001085 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001086 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001087 GLSLstd450UMin, args, out);
1088 break;
1089 }
1090 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001091 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001092 SkASSERT(args.size() == 3);
John Stilescc2d9cc2021-07-09 17:38:41 -04001093 if (arguments[2]->type().componentType().isBoolean()) {
1094 // Use OpSelect to implement Boolean mix().
1095 SpvId falseId = this->writeExpression(*arguments[0], out);
1096 SpvId trueId = this->writeExpression(*arguments[1], out);
1097 SpvId conditionId = this->writeExpression(*arguments[2], out);
1098 this->writeInstruction(SpvOpSelect, this->getType(arguments[0]->type()), result,
1099 conditionId, trueId, falseId, out);
1100 } else {
1101 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
1102 SpvOpUndef, args, out);
1103 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001104 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001105 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001106 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001107 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001108 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001109 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001110 finalArgs.push_back(arguments[0]->clone());
John Stiles9ce80f72021-03-11 22:35:19 -05001111 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/0));
1112 finalArgs.push_back(FloatLiteral::Make(fContext, /*offset=*/-1, /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001113 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001114 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001115 GLSLstd450UClamp, spvArgs, out);
1116 break;
1117 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001118 case kSmoothStep_SpecialIntrinsic: {
1119 std::vector<SpvId> args = this->vectorize(arguments, out);
1120 SkASSERT(args.size() == 3);
1121 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1122 SpvOpUndef, args, out);
1123 break;
1124 }
1125 case kStep_SpecialIntrinsic: {
1126 std::vector<SpvId> args = this->vectorize(arguments, out);
1127 SkASSERT(args.size() == 2);
1128 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1129 SpvOpUndef, args, out);
1130 break;
1131 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001132 case kMatrixCompMult_SpecialIntrinsic: {
1133 SkASSERT(arguments.size() == 2);
1134 SpvId lhs = this->writeExpression(*arguments[0], out);
1135 SpvId rhs = this->writeExpression(*arguments[1], out);
John Stiles43b593c2021-05-13 22:03:27 -04001136 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
Brian Osmand1b593f2020-12-28 13:00:46 -05001137 break;
1138 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001139 }
1140 return result;
1141}
1142
John Stilesec241542021-02-11 17:50:09 -05001143namespace {
1144struct TempVar {
1145 SpvId spvId;
1146 const Type* type;
1147 std::unique_ptr<SPIRVCodeGenerator::LValue> lvalue;
1148};
1149}
1150
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001151SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001152 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -04001153 if (function.isIntrinsic() && !function.definition()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001154 return this->writeIntrinsicCall(c, out);
1155 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001156 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001157 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001158 if (entry == fFunctionMap.end()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001159 fErrors.error(c.fOffset, "function '" + function.description() + "' is not defined");
1160 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001161 }
John Stilesec241542021-02-11 17:50:09 -05001162 // Temp variables are used to write back out-parameters after the function call is complete.
1163 std::vector<TempVar> tempVars;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001164 std::vector<SpvId> argumentIds;
1165 for (size_t i = 0; i < arguments.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -05001166 // id of temporary variable that we will use to hold this argument, or 0 if it is being
ethannicholasb3058bd2016-07-01 08:22:01 -07001167 // passed directly
1168 SpvId tmpVar;
1169 // if we need a temporary var to store this argument, this is the value to store in the var
1170 SpvId tmpValueId;
Ethan Nicholased84b732020-10-08 11:45:44 -04001171 if (is_out(*function.parameters()[i])) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001172 std::unique_ptr<LValue> lv = this->getLValue(*arguments[i], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001173 SpvId ptr = lv->getPointer();
Ethan Nicholase0707b72021-03-17 11:16:41 -04001174 if (ptr != (SpvId) -1 && lv->isMemoryObjectPointer()) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001175 argumentIds.push_back(ptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001176 continue;
1177 } else {
1178 // lvalue cannot simply be read and written via a pointer (e.g. a swizzle). Need to
1179 // copy it into a temp, call the function, read the value out of the temp, and then
1180 // update the lvalue.
1181 tmpValueId = lv->load(out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001182 tmpVar = this->nextId(nullptr);
John Stilesec241542021-02-11 17:50:09 -05001183 tempVars.push_back(TempVar{tmpVar, &arguments[i]->type(), std::move(lv)});
ethannicholasb3058bd2016-07-01 08:22:01 -07001184 }
1185 } else {
John Stilesec241542021-02-11 17:50:09 -05001186 // See getFunctionType for an explanation of why we're always using pointer parameters.
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001187 tmpValueId = this->writeExpression(*arguments[i], out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001188 tmpVar = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001189 }
Greg Daniel64773e62016-11-22 09:44:03 -05001190 this->writeInstruction(SpvOpVariable,
John Stilesec241542021-02-11 17:50:09 -05001191 this->getPointerType(arguments[i]->type(), SpvStorageClassFunction),
Greg Daniel64773e62016-11-22 09:44:03 -05001192 tmpVar,
ethannicholasb3058bd2016-07-01 08:22:01 -07001193 SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07001194 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001195 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001196 argumentIds.push_back(tmpVar);
ethannicholasb3058bd2016-07-01 08:22:01 -07001197 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001198 SpvId result = this->nextId(nullptr);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001199 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001200 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001201 this->writeWord(result, out);
1202 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001203 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001204 this->writeWord(id, out);
1205 }
John Stilesec241542021-02-11 17:50:09 -05001206 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
1207 for (const TempVar& tempVar : tempVars) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001208 SpvId load = this->nextId(tempVar.type);
John Stilesec241542021-02-11 17:50:09 -05001209 this->writeInstruction(SpvOpLoad, getType(*tempVar.type), load, tempVar.spvId, out);
John Stilesec241542021-02-11 17:50:09 -05001210 tempVar.lvalue->store(load, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001211 }
1212 return result;
1213}
1214
John Stiles2938eea2021-04-01 18:58:25 -04001215SpvId SPIRVCodeGenerator::writeConstantVector(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001216 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001217 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001218
John Stiles9cfaa4f2021-01-06 17:52:00 -05001219 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001220 SPIRVVectorConstant key{this->getType(type),
1221 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001222
John Stiles21a50ec2021-04-06 14:49:36 -04001223 for (int n = 0; n < type.columns(); n++) {
1224 const Expression* expr = c.getConstantSubexpression(n);
1225 if (!expr) {
1226 SkDEBUGFAILF("writeConstantVector: %s not actually constant", c.description().c_str());
1227 return (SpvId)-1;
John Stiles9cfaa4f2021-01-06 17:52:00 -05001228 }
John Stiles21a50ec2021-04-06 14:49:36 -04001229 key.fValueId[n] = this->writeExpression(*expr, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001230 }
John Stilescd806892021-01-06 13:33:31 -05001231
1232 // Check to see if we've already synthesized this vector constant.
1233 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1234 if (newlyCreated) {
1235 // Emit an OpConstantComposite instruction for this constant.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001236 SpvId result = this->nextId(&type);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001237 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001238 this->writeWord(key.fTypeId, fConstantBuffer);
1239 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001240 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001241 this->writeWord(key.fValueId[i], fConstantBuffer);
1242 }
1243 iter->second = result;
1244 }
1245 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001246}
1247
John Stilesb14a8192021-04-05 11:40:46 -04001248SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
1249 const Type& inputType,
1250 const Type& outputType,
1251 OutputStream& out) {
1252 if (outputType.isFloat()) {
1253 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
1254 }
1255 if (outputType.isSigned()) {
1256 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
1257 }
1258 if (outputType.isUnsigned()) {
1259 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
1260 }
1261 if (outputType.isBoolean()) {
1262 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
1263 }
1264
1265 fErrors.error(-1, "unsupported cast: " + inputType.description() +
1266 " to " + outputType.description());
1267 return inputExprId;
1268}
1269
John Stilesfd7252f2021-04-04 22:24:40 -04001270SpvId SPIRVCodeGenerator::writeFloatConstructor(const AnyConstructor& c, OutputStream& out) {
1271 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001272 SkASSERT(c.type().isFloat());
John Stilesfd7252f2021-04-04 22:24:40 -04001273 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001274 SpvId expressionId = this->writeExpression(ctorExpr, out);
1275 return this->castScalarToFloat(expressionId, ctorExpr.type(), c.type(), out);
1276}
1277
1278SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
1279 const Type& outputType, OutputStream& out) {
1280 // Casting a float to float is a no-op.
1281 if (inputType.isFloat()) {
1282 return inputId;
1283 }
1284
1285 // Given the input type, generate the appropriate instruction to cast to float.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001286 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001287 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001288 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
John Stiles9ce80f72021-03-11 22:35:19 -05001289 FloatLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001290 SpvId oneID = this->writeFloatLiteral(one);
John Stiles9ce80f72021-03-11 22:35:19 -05001291 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001292 SpvId zeroID = this->writeFloatLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001293 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1294 inputId, oneID, zeroID, out);
1295 } else if (inputType.isSigned()) {
1296 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
1297 } else if (inputType.isUnsigned()) {
1298 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001299 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001300 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
1301 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001302 }
1303 return result;
1304}
1305
John Stilesfd7252f2021-04-04 22:24:40 -04001306SpvId SPIRVCodeGenerator::writeIntConstructor(const AnyConstructor& c, OutputStream& out) {
1307 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001308 SkASSERT(c.type().isSigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001309 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001310 SpvId expressionId = this->writeExpression(ctorExpr, out);
1311 return this->castScalarToSignedInt(expressionId, ctorExpr.type(), c.type(), out);
1312}
1313
1314SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
1315 const Type& outputType, OutputStream& out) {
1316 // Casting a signed int to signed int is a no-op.
1317 if (inputType.isSigned()) {
1318 return inputId;
1319 }
1320
1321 // Given the input type, generate the appropriate instruction to cast to signed int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001322 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001323 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001324 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
John Stiles54e7c052021-01-11 14:22:36 -05001325 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001326 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001327 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001328 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001329 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1330 inputId, oneID, zeroID, out);
1331 } else if (inputType.isFloat()) {
1332 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
1333 } else if (inputType.isUnsigned()) {
1334 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
1335 } else {
1336 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
1337 inputType.description().c_str());
1338 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001339 }
1340 return result;
1341}
1342
John Stilesfd7252f2021-04-04 22:24:40 -04001343SpvId SPIRVCodeGenerator::writeUIntConstructor(const AnyConstructor& c, OutputStream& out) {
1344 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001345 SkASSERT(c.type().isUnsigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001346 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001347 SpvId expressionId = this->writeExpression(ctorExpr, out);
1348 return this->castScalarToUnsignedInt(expressionId, ctorExpr.type(), c.type(), out);
1349}
1350
1351SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
1352 const Type& outputType, OutputStream& out) {
1353 // Casting an unsigned int to unsigned int is a no-op.
1354 if (inputType.isUnsigned()) {
1355 return inputId;
1356 }
1357
John Stiles48c28842021-01-14 11:05:03 -05001358 // Given the input type, generate the appropriate instruction to cast to unsigned int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001359 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001360 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001361 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
John Stiles54e7c052021-01-11 14:22:36 -05001362 IntLiteral one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001363 SpvId oneID = this->writeIntLiteral(one);
John Stiles54e7c052021-01-11 14:22:36 -05001364 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stilesba4b0e92021-01-05 13:55:39 -05001365 SpvId zeroID = this->writeIntLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001366 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1367 inputId, oneID, zeroID, out);
1368 } else if (inputType.isFloat()) {
1369 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
1370 } else if (inputType.isSigned()) {
1371 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001372 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001373 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
1374 inputType.description().c_str());
1375 return (SpvId)-1;
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001376 }
1377 return result;
1378}
1379
John Stilesfd7252f2021-04-04 22:24:40 -04001380SpvId SPIRVCodeGenerator::writeBooleanConstructor(const AnyConstructor& c, OutputStream& out) {
1381 SkASSERT(c.argumentSpan().size() == 1);
John Stilesa60fb172021-01-14 11:06:20 -05001382 SkASSERT(c.type().isBoolean());
John Stilesfd7252f2021-04-04 22:24:40 -04001383 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesa60fb172021-01-14 11:06:20 -05001384 SpvId expressionId = this->writeExpression(ctorExpr, out);
1385 return this->castScalarToBoolean(expressionId, ctorExpr.type(), c.type(), out);
1386}
1387
John Stiles48c28842021-01-14 11:05:03 -05001388SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
1389 const Type& outputType, OutputStream& out) {
1390 // Casting a bool to bool is a no-op.
1391 if (inputType.isBoolean()) {
1392 return inputId;
1393 }
1394
1395 // Given the input type, generate the appropriate instruction to cast to bool.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001396 SpvId result = this->nextId(nullptr);
John Stiles48c28842021-01-14 11:05:03 -05001397 if (inputType.isSigned()) {
1398 // Synthesize a boolean result by comparing the input against a signed zero literal.
1399 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
1400 SpvId zeroID = this->writeIntLiteral(zero);
1401 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1402 inputId, zeroID, out);
1403 } else if (inputType.isUnsigned()) {
1404 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
1405 IntLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
1406 SpvId zeroID = this->writeIntLiteral(zero);
1407 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1408 inputId, zeroID, out);
1409 } else if (inputType.isFloat()) {
1410 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
1411 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
1412 SpvId zeroID = this->writeFloatLiteral(zero);
1413 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
1414 inputId, zeroID, out);
1415 } else {
1416 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
1417 return (SpvId)-1;
1418 }
1419 return result;
1420}
1421
Ethan Nicholas84645e32017-02-09 13:57:14 -05001422void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001423 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05001424 FloatLiteral zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001425 SpvId zeroId = this->writeFloatLiteral(zero);
1426 std::vector<SpvId> columnIds;
John Stiles392d8292021-04-09 12:14:03 -04001427 columnIds.reserve(type.columns());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001428 for (int column = 0; column < type.columns(); column++) {
1429 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1430 out);
John Stiles392d8292021-04-09 12:14:03 -04001431 this->writeWord(this->getType(type.componentType().toCompound(
1432 fContext, /*columns=*/type.rows(), /*rows=*/1)),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001433 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001434 SpvId columnId = this->nextId(&type);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001435 this->writeWord(columnId, out);
1436 columnIds.push_back(columnId);
John Stiles392d8292021-04-09 12:14:03 -04001437 for (int row = 0; row < type.rows(); row++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001438 this->writeWord(row == column ? diagonal : zeroId, out);
1439 }
1440 }
1441 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1442 out);
1443 this->writeWord(this->getType(type), out);
1444 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001445 for (SpvId columnId : columnIds) {
1446 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001447 }
1448}
1449
John Stiles268a73f2021-04-07 12:30:22 -04001450SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
1451 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001452 SkASSERT(srcType.isMatrix());
1453 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001454 SkASSERT(srcType.componentType() == dstType.componentType());
John Stiles268a73f2021-04-07 12:30:22 -04001455 SpvId id = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001456 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1457 srcType.rows(),
1458 1));
1459 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1460 dstType.rows(),
1461 1));
John Stiles92671832021-04-06 09:24:55 -04001462 SkASSERT(dstType.componentType().isFloat());
1463 FloatLiteral zero(/*offset=*/-1, /*value=*/0.0, &dstType.componentType());
1464 const SpvId zeroId = this->writeFloatLiteral(zero);
1465 FloatLiteral one(/*offset=*/-1, /*value=*/1.0, &dstType.componentType());
1466 const SpvId oneId = this->writeFloatLiteral(one);
1467
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001468 SpvId columns[4];
1469 for (int i = 0; i < dstType.columns(); i++) {
1470 if (i < srcType.columns()) {
1471 // we're still inside the src matrix, copy the column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001472 SpvId srcColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001473 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1474 SpvId dstColumn;
1475 if (srcType.rows() == dstType.rows()) {
1476 // columns are equal size, don't need to do anything
1477 dstColumn = srcColumn;
1478 }
1479 else if (dstType.rows() > srcType.rows()) {
1480 // dst column is bigger, need to zero-pad it
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001481 dstColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001482 int delta = dstType.rows() - srcType.rows();
1483 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1484 this->writeWord(dstColumnType, out);
1485 this->writeWord(dstColumn, out);
1486 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001487 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
1488 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001489 }
1490 }
1491 else {
1492 // dst column is smaller, need to swizzle the src column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001493 dstColumn = this->nextId(&dstType);
John Stiles92671832021-04-06 09:24:55 -04001494 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001495 this->writeWord(dstColumnType, out);
1496 this->writeWord(dstColumn, out);
1497 this->writeWord(srcColumn, out);
1498 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001499 for (int j = 0; j < dstType.rows(); j++) {
John Stilesf621e232020-08-25 13:33:02 -04001500 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001501 }
1502 }
1503 columns[i] = dstColumn;
1504 } else {
John Stiles92671832021-04-06 09:24:55 -04001505 // we're past the end of the src matrix, need to synthesize an identity-matrix column
1506 SpvId identityColumn = this->nextId(&dstType);
1507 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1508 this->writeWord(dstColumnType, out);
1509 this->writeWord(identityColumn, out);
1510 for (int j = 0; j < dstType.rows(); ++j) {
1511 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001512 }
John Stiles92671832021-04-06 09:24:55 -04001513 columns[i] = identityColumn;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001514 }
1515 }
1516 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1517 this->writeWord(this->getType(dstType), out);
1518 this->writeWord(id, out);
1519 for (int i = 0; i < dstType.columns(); i++) {
1520 this->writeWord(columns[i], out);
1521 }
John Stiles268a73f2021-04-07 12:30:22 -04001522 return id;
Ethan Nicholas84645e32017-02-09 13:57:14 -05001523}
1524
John Stilesbeb2fbf2021-07-08 18:54:39 -04001525void SPIRVCodeGenerator::addColumnEntry(const Type& columnType,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001526 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001527 std::vector<SpvId>* columnIds,
John Stilesbeb2fbf2021-07-08 18:54:39 -04001528 int rows,
1529 SpvId entry,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001530 OutputStream& out) {
John Stilesbeb2fbf2021-07-08 18:54:39 -04001531 SkASSERT((int)currentColumn->size() < rows);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001532 currentColumn->push_back(entry);
John Stilesbeb2fbf2021-07-08 18:54:39 -04001533 if ((int)currentColumn->size() == rows) {
1534 // Synthesize this column into a vector.
1535 SpvId columnId = this->writeComposite(*currentColumn, columnType, out);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001536 columnIds->push_back(columnId);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001537 currentColumn->clear();
1538 }
1539}
1540
John Stiles8cad6372021-04-07 12:31:13 -04001541SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001542 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001543 SkASSERT(type.isMatrix());
John Stiles2bec8ab2021-04-06 18:40:04 -04001544 SkASSERT(!c.arguments().empty());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001545 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001546 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1547 // an instruction
1548 std::vector<SpvId> arguments;
John Stiles2bec8ab2021-04-06 18:40:04 -04001549 arguments.reserve(c.arguments().size());
1550 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1551 arguments.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001552 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001553
John Stiles268a73f2021-04-07 12:30:22 -04001554 if (arguments.size() == 1 && arg0Type.isVector()) {
1555 // Special-case handling of float4 -> mat2x2.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001556 SkASSERT(type.rows() == 2 && type.columns() == 2);
1557 SkASSERT(arg0Type.columns() == 4);
1558 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001559 SpvId v[4];
1560 for (int i = 0; i < 4; ++i) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001561 v[i] = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001562 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1563 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001564 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001565 const Type& vecType = type.componentType().toCompound(fContext, /*columns=*/2, /*rows=*/1);
1566 SpvId v0v1 = this->writeComposite({v[0], v[1]}, vecType, out);
1567 SpvId v2v3 = this->writeComposite({v[2], v[3]}, vecType, out);
1568 return this->writeComposite({v0v1, v2v3}, type, out);
1569 }
1570
1571 int rows = type.rows();
1572 const Type& columnType = type.componentType().toCompound(fContext,
1573 /*columns=*/rows, /*rows=*/1);
1574 // SpvIds of completed columns of the matrix.
1575 std::vector<SpvId> columnIds;
1576 // SpvIds of scalars we have written to the current column so far.
1577 std::vector<SpvId> currentColumn;
1578 for (size_t i = 0; i < arguments.size(); i++) {
1579 const Type& argType = c.arguments()[i]->type();
1580 if (currentColumn.empty() && argType.isVector() && argType.columns() == rows) {
1581 // This vector is a complete matrix column by itself and can be used as-is.
1582 columnIds.push_back(arguments[i]);
1583 } else if (argType.columns() == 1) {
1584 // This argument is a lone scalar and can be added to the current column as-is.
1585 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, arguments[i], out);
1586 } else {
1587 // This argument needs to be decomposed into its constituent scalars.
1588 SpvId componentType = this->getType(argType.componentType());
1589 for (int j = 0; j < argType.columns(); ++j) {
1590 SpvId swizzle = this->nextId(&argType);
1591 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1592 arguments[i], j, out);
1593 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, swizzle, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001594 }
1595 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001596 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001597 SkASSERT(columnIds.size() == (size_t) type.columns());
1598 return this->writeComposite(columnIds, type, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001599}
1600
John Stiles8cad6372021-04-07 12:31:13 -04001601SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1602 OutputStream& out) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001603 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
1604 : this->writeVectorConstructor(c, out);
1605}
1606
John Stiles8cad6372021-04-07 12:31:13 -04001607SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001608 const Type& type = c.type();
John Stilesd986f472021-04-06 15:54:43 -04001609 const Type& componentType = type.componentType();
John Stiles9aeed132020-11-24 17:36:06 -05001610 SkASSERT(type.isVector());
John Stilesd986f472021-04-06 15:54:43 -04001611
1612 if (c.isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001613 return this->writeConstantVector(c);
1614 }
John Stilesd986f472021-04-06 15:54:43 -04001615
ethannicholasb3058bd2016-07-01 08:22:01 -07001616 std::vector<SpvId> arguments;
John Stiles6de2e1d2021-07-09 12:41:55 -04001617 arguments.reserve(c.arguments().size());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001618 for (size_t i = 0; i < c.arguments().size(); i++) {
1619 const Type& argType = c.arguments()[i]->type();
John Stilesd986f472021-04-06 15:54:43 -04001620 SkASSERT(componentType == argType.componentType());
John Stiles48c28842021-01-14 11:05:03 -05001621
John Stiles6de2e1d2021-07-09 12:41:55 -04001622 SpvId arg = this->writeExpression(*c.arguments()[i], out);
1623 if (argType.isMatrix()) {
1624 // CompositeConstruct cannot take a 2x2 matrix as an input, so we need to extract out
1625 // each scalar separately.
1626 SkASSERT(argType.rows() == 2);
1627 SkASSERT(argType.columns() == 2);
1628 for (int j = 0; j < 4; ++j) {
1629 SpvId componentId = this->nextId(&componentType);
1630 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
1631 componentId, arg, j / 2, j % 2, out);
1632 arguments.push_back(componentId);
1633 }
1634 } else if (argType.isVector()) {
John Stilesd986f472021-04-06 15:54:43 -04001635 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
1636 // vector arguments at all, so we always extract each vector component and pass them
1637 // into OpCompositeConstruct individually.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001638 for (int j = 0; j < argType.columns(); j++) {
John Stilesd986f472021-04-06 15:54:43 -04001639 SpvId componentId = this->nextId(&componentType);
1640 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
John Stiles6de2e1d2021-07-09 12:41:55 -04001641 componentId, arg, j, out);
John Stilesd986f472021-04-06 15:54:43 -04001642 arguments.push_back(componentId);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001643 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001644 } else {
John Stiles6de2e1d2021-07-09 12:41:55 -04001645 arguments.push_back(arg);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001646 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001647 }
John Stilesb14a8192021-04-05 11:40:46 -04001648
1649 return this->writeComposite(arguments, type, out);
1650}
1651
1652SpvId SPIRVCodeGenerator::writeComposite(const std::vector<SpvId>& arguments,
1653 const Type& type,
1654 OutputStream& out) {
John Stilesd47330f2021-04-08 23:25:52 -04001655 SkASSERT(arguments.size() == (type.isStruct() ? type.fields().size() : (size_t)type.columns()));
John Stiles2938eea2021-04-01 18:58:25 -04001656
Ethan Nicholas7f015882021-03-23 14:16:52 -04001657 SpvId result = this->nextId(&type);
John Stiles2938eea2021-04-01 18:58:25 -04001658 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1659 this->writeWord(this->getType(type), out);
1660 this->writeWord(result, out);
1661 for (SpvId id : arguments) {
1662 this->writeWord(id, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001663 }
1664 return result;
1665}
1666
John Stiles2938eea2021-04-01 18:58:25 -04001667SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, OutputStream& out) {
1668 // Use writeConstantVector to deduplicate constant splats.
1669 if (c.isCompileTimeConstant()) {
1670 return this->writeConstantVector(c);
1671 }
1672
1673 // Write the splat argument.
1674 SpvId argument = this->writeExpression(*c.argument(), out);
1675
1676 // Generate a OpCompositeConstruct which repeats the argument N times.
John Stilesb14a8192021-04-05 11:40:46 -04001677 std::vector<SpvId> arguments(/*count*/ c.type().columns(), /*value*/ argument);
1678 return this->writeComposite(arguments, c.type(), out);
John Stiles2938eea2021-04-01 18:58:25 -04001679}
1680
1681
John Stilesd47330f2021-04-08 23:25:52 -04001682SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, OutputStream& out) {
1683 SkASSERT(c.type().isArray() || c.type().isStruct());
1684 auto ctorArgs = c.argumentSpan();
1685
Ethan Nicholasbd553222017-07-18 15:54:59 -04001686 std::vector<SpvId> arguments;
John Stilesd47330f2021-04-08 23:25:52 -04001687 arguments.reserve(ctorArgs.size());
1688 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
1689 arguments.push_back(this->writeExpression(*arg, out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001690 }
John Stilesd47330f2021-04-08 23:25:52 -04001691
1692 return this->writeComposite(arguments, c.type(), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001693}
1694
John Stilesfd7252f2021-04-04 22:24:40 -04001695SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1696 OutputStream& out) {
1697 const Type& type = c.type();
1698 if (this->getActualType(type) == this->getActualType(c.argument()->type())) {
1699 return this->writeExpression(*c.argument(), out);
1700 }
John Stilesb14a8192021-04-05 11:40:46 -04001701
1702 const Expression& ctorExpr = *c.argument();
1703 SpvId expressionId = this->writeExpression(ctorExpr, out);
1704 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
1705}
1706
John Stiles8cad6372021-04-07 12:31:13 -04001707SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
1708 OutputStream& out) {
John Stilesb14a8192021-04-05 11:40:46 -04001709 const Type& ctorType = c.type();
1710 const Type& argType = c.argument()->type();
John Stiles268a73f2021-04-07 12:30:22 -04001711 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
John Stilesb14a8192021-04-05 11:40:46 -04001712
John Stiles268a73f2021-04-07 12:30:22 -04001713 // Write the composite that we are casting. If the actual type matches, we are done.
1714 SpvId compositeId = this->writeExpression(*c.argument(), out);
John Stilesb14a8192021-04-05 11:40:46 -04001715 if (this->getActualType(ctorType) == this->getActualType(argType)) {
John Stiles268a73f2021-04-07 12:30:22 -04001716 return compositeId;
1717 }
1718
1719 // writeMatrixCopy can cast matrices to a different type.
1720 if (ctorType.isMatrix()) {
1721 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
John Stilesfd7252f2021-04-04 22:24:40 -04001722 }
John Stilesb14a8192021-04-05 11:40:46 -04001723
1724 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
John Stilesd986f472021-04-06 15:54:43 -04001725 // components and convert each one manually.
John Stilesb14a8192021-04-05 11:40:46 -04001726 const Type& srcType = argType.componentType();
1727 const Type& dstType = ctorType.componentType();
1728
1729 std::vector<SpvId> arguments;
John Stiles268a73f2021-04-07 12:30:22 -04001730 arguments.reserve(argType.columns());
John Stilesb14a8192021-04-05 11:40:46 -04001731 for (int index = 0; index < argType.columns(); ++index) {
1732 SpvId componentId = this->nextId(&srcType);
1733 this->writeInstruction(SpvOpCompositeExtract, this->getType(srcType), componentId,
John Stiles268a73f2021-04-07 12:30:22 -04001734 compositeId, index, out);
John Stilesb14a8192021-04-05 11:40:46 -04001735 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
John Stilesfd7252f2021-04-04 22:24:40 -04001736 }
John Stilesb14a8192021-04-05 11:40:46 -04001737
1738 return this->writeComposite(arguments, ctorType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001739}
1740
John Stilese1182782021-03-30 22:09:37 -04001741SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
1742 OutputStream& out) {
1743 const Type& type = c.type();
1744 SkASSERT(type.isMatrix());
1745 SkASSERT(c.argument()->type().isScalar());
1746
1747 // Write out the scalar argument.
1748 SpvId argument = this->writeExpression(*c.argument(), out);
1749
1750 // Build the diagonal matrix.
1751 SpvId result = this->nextId(&type);
1752 this->writeUniformScaleMatrix(result, argument, type, out);
1753 return result;
1754}
1755
John Stiles5abb9e12021-04-06 13:47:19 -04001756SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1757 OutputStream& out) {
1758 // Write the input matrix.
1759 SpvId argument = this->writeExpression(*c.argument(), out);
1760
1761 // Use matrix-copy to resize the input matrix to its new size.
John Stiles268a73f2021-04-07 12:30:22 -04001762 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
John Stiles5abb9e12021-04-06 13:47:19 -04001763}
1764
John Stiles9485b552021-01-27 11:47:00 -05001765static SpvStorageClass_ get_storage_class(const Variable& var,
1766 SpvStorageClass_ fallbackStorageClass) {
1767 const Modifiers& modifiers = var.modifiers();
ethannicholasb3058bd2016-07-01 08:22:01 -07001768 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001769 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001770 return SpvStorageClassInput;
John Stiles9485b552021-01-27 11:47:00 -05001771 }
1772 if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001773 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001774 return SpvStorageClassOutput;
John Stiles9485b552021-01-27 11:47:00 -05001775 }
1776 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001777 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001778 return SpvStorageClassPushConstant;
1779 }
John Stiles9485b552021-01-27 11:47:00 -05001780 if (var.type().typeKind() == Type::TypeKind::kSampler ||
1781 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
1782 var.type().typeKind() == Type::TypeKind::kTexture) {
1783 return SpvStorageClassUniformConstant;
1784 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001785 return SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07001786 }
John Stiles9485b552021-01-27 11:47:00 -05001787 return fallbackStorageClass;
ethannicholasb3058bd2016-07-01 08:22:01 -07001788}
1789
John Stiles9485b552021-01-27 11:47:00 -05001790static SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001791 switch (expr.kind()) {
1792 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001793 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001794 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001795 return SpvStorageClassFunction;
1796 }
John Stiles9485b552021-01-27 11:47:00 -05001797 return get_storage_class(var, SpvStorageClassPrivate);
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001798 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001799 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001800 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001801 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001802 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001803 default:
1804 return SpvStorageClassFunction;
1805 }
1806}
1807
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001808std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001809 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001810 switch (expr.kind()) {
1811 case Expression::Kind::kIndex: {
John Stiles0693fb82021-01-22 18:27:52 -05001812 const IndexExpression& indexExpr = expr.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001813 chain = this->getAccessChain(*indexExpr.base(), out);
1814 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001815 break;
1816 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001817 case Expression::Kind::kFieldAccess: {
John Stiles0693fb82021-01-22 18:27:52 -05001818 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001819 chain = this->getAccessChain(*fieldExpr.base(), out);
John Stiles9ce80f72021-03-11 22:35:19 -05001820 IntLiteral index(/*offset=*/-1, fieldExpr.fieldIndex(), fContext.fTypes.fInt.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07001821 chain.push_back(this->writeIntLiteral(index));
1822 break;
1823 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001824 default: {
1825 SpvId id = this->getLValue(expr, out)->getPointer();
John Stiles3f14d282021-02-05 09:31:04 -05001826 SkASSERT(id != (SpvId) -1);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001827 chain.push_back(id);
1828 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001829 }
1830 return chain;
1831}
1832
1833class PointerLValue : public SPIRVCodeGenerator::LValue {
1834public:
Ethan Nicholase0707b72021-03-17 11:16:41 -04001835 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001836 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001837 : fGen(gen)
1838 , fPointer(pointer)
Ethan Nicholase0707b72021-03-17 11:16:41 -04001839 , fIsMemoryObject(isMemoryObject)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001840 , fType(type)
1841 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001842
John Stiles1cf2c8d2020-08-13 22:58:04 -04001843 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001844 return fPointer;
1845 }
1846
Ethan Nicholase0707b72021-03-17 11:16:41 -04001847 bool isMemoryObjectPointer() const override {
1848 return fIsMemoryObject;
1849 }
1850
John Stiles1cf2c8d2020-08-13 22:58:04 -04001851 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001852 SpvId result = fGen.nextId(fPrecision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001853 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1854 return result;
1855 }
1856
John Stiles1cf2c8d2020-08-13 22:58:04 -04001857 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001858 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1859 }
1860
1861private:
1862 SPIRVCodeGenerator& fGen;
1863 const SpvId fPointer;
Ethan Nicholase0707b72021-03-17 11:16:41 -04001864 const bool fIsMemoryObject;
ethannicholasb3058bd2016-07-01 08:22:01 -07001865 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001866 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001867};
1868
1869class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1870public:
John Stiles750109b2020-10-30 13:45:46 -04001871 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001872 const Type& baseType, const Type& swizzleType)
ethannicholasb3058bd2016-07-01 08:22:01 -07001873 : fGen(gen)
1874 , fVecPointer(vecPointer)
1875 , fComponents(components)
John Stiles3f14d282021-02-05 09:31:04 -05001876 , fBaseType(&baseType)
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001877 , fSwizzleType(&swizzleType) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001878
John Stiles3f14d282021-02-05 09:31:04 -05001879 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
1880 ComponentArray updatedSwizzle;
1881 for (int8_t component : components) {
1882 if (component < 0 || component >= fComponents.count()) {
1883 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
1884 return false;
1885 }
1886 updatedSwizzle.push_back(fComponents[component]);
1887 }
1888 fComponents = updatedSwizzle;
1889 fSwizzleType = &newType;
1890 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001891 }
1892
John Stiles1cf2c8d2020-08-13 22:58:04 -04001893 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001894 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001895 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001896 SpvId result = fGen.nextId(fBaseType);
ethannicholasb3058bd2016-07-01 08:22:01 -07001897 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
John Stiles3f14d282021-02-05 09:31:04 -05001898 fGen.writeWord(fGen.getType(*fSwizzleType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001899 fGen.writeWord(result, out);
1900 fGen.writeWord(base, out);
1901 fGen.writeWord(base, out);
1902 for (int component : fComponents) {
1903 fGen.writeWord(component, out);
1904 }
1905 return result;
1906 }
1907
John Stiles1cf2c8d2020-08-13 22:58:04 -04001908 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001909 // use OpVectorShuffle to mix and match the vector components. We effectively create
1910 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001911 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001912 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001913 // float3L = ...;
1914 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001915 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001916 // 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 -07001917 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1918 // (3, 1, 4).
Ethan Nicholas7f015882021-03-23 14:16:52 -04001919 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001920 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001921 SpvId shuffle = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001922 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
1923 fGen.writeWord(fGen.getType(*fBaseType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001924 fGen.writeWord(shuffle, out);
1925 fGen.writeWord(base, out);
1926 fGen.writeWord(value, out);
John Stiles3f14d282021-02-05 09:31:04 -05001927 for (int i = 0; i < fBaseType->columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001928 // current offset into the virtual vector, defaults to pulling the unmodified
1929 // value from the left side
1930 int offset = i;
1931 // check to see if we are writing this component
1932 for (size_t j = 0; j < fComponents.size(); j++) {
1933 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001934 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001935 // the correct component of the right side instead of preserving the
1936 // value from the left
John Stiles3f14d282021-02-05 09:31:04 -05001937 offset = (int) (j + fBaseType->columns());
ethannicholasb3058bd2016-07-01 08:22:01 -07001938 break;
1939 }
1940 }
1941 fGen.writeWord(offset, out);
1942 }
1943 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1944 }
1945
1946private:
1947 SPIRVCodeGenerator& fGen;
1948 const SpvId fVecPointer;
John Stiles3f14d282021-02-05 09:31:04 -05001949 ComponentArray fComponents;
1950 const Type* fBaseType;
1951 const Type* fSwizzleType;
ethannicholasb3058bd2016-07-01 08:22:01 -07001952};
1953
John Stilese40d1662021-01-29 10:08:50 -05001954int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
1955 auto iter = fTopLevelUniformMap.find(&var);
1956 return (iter != fTopLevelUniformMap.end()) ? iter->second : -1;
1957}
1958
Greg Daniel64773e62016-11-22 09:44:03 -05001959std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001960 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001961 const Type& type = expr.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001962 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
Ethan Nicholase6592142020-09-08 10:22:09 -04001963 switch (expr.kind()) {
1964 case Expression::Kind::kVariableReference: {
John Stiles0de76f72021-01-29 09:19:39 -05001965 const Variable& var = *expr.as<VariableReference>().variable();
John Stilese40d1662021-01-29 10:08:50 -05001966 int uniformIdx = this->findUniformFieldIndex(var);
1967 if (uniformIdx >= 0) {
John Stiles9ce80f72021-03-11 22:35:19 -05001968 IntLiteral uniformIdxLiteral{/*offset=*/-1, uniformIdx, fContext.fTypes.fInt.get()};
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001969 SpvId memberId = this->nextId(nullptr);
John Stilese40d1662021-01-29 10:08:50 -05001970 SpvId typeId = this->getPointerType(type, SpvStorageClassUniform);
1971 SpvId uniformIdxId = this->writeIntLiteral(uniformIdxLiteral);
1972 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
1973 uniformIdxId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04001974 return std::make_unique<PointerLValue>(*this, memberId,
1975 /*isMemoryObjectPointer=*/true,
1976 this->getType(type), precision);
John Stilese40d1662021-01-29 10:08:50 -05001977 }
1978 SpvId typeId;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001979 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
John Stilesad2d4942020-12-11 16:55:58 -05001980 typeId = this->getType(*Type::MakeArrayType("sk_in", var.type().componentType(),
1981 fSkInCount));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001982 } else {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05001983 typeId = this->getType(type, this->memoryLayoutForVariable(var));
Ethan Nicholas5226b772018-05-03 16:20:41 -04001984 }
ethannicholasd598f792016-07-25 10:08:54 -07001985 auto entry = fVariableMap.find(&var);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001986 SkASSERT(entry != fVariableMap.end());
Ethan Nicholase0707b72021-03-17 11:16:41 -04001987 return std::make_unique<PointerLValue>(*this, entry->second,
1988 /*isMemoryObjectPointer=*/true,
1989 typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001990 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001991 case Expression::Kind::kIndex: // fall through
1992 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07001993 std::vector<SpvId> chain = this->getAccessChain(expr, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001994 SpvId member = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07001995 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001996 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001997 this->writeWord(member, out);
1998 for (SpvId idx : chain) {
1999 this->writeWord(idx, out);
2000 }
Ethan Nicholase0707b72021-03-17 11:16:41 -04002001 return std::make_unique<PointerLValue>(*this, member, /*isMemoryObjectPointer=*/false,
2002 this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002003 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002004 case Expression::Kind::kSwizzle: {
John Stiles0693fb82021-01-22 18:27:52 -05002005 const Swizzle& swizzle = expr.as<Swizzle>();
John Stiles3f14d282021-02-05 09:31:04 -05002006 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
2007 if (lvalue->applySwizzle(swizzle.components(), type)) {
2008 return lvalue;
2009 }
2010 SpvId base = lvalue->getPointer();
2011 if (base == (SpvId) -1) {
John Stiles5570c512020-11-19 17:58:07 -05002012 fErrors.error(swizzle.fOffset, "unable to retrieve lvalue from swizzle");
2013 }
John Stiles3f14d282021-02-05 09:31:04 -05002014 if (swizzle.components().size() == 1) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002015 SpvId member = this->nextId(nullptr);
John Stilesb5db4822021-01-21 13:04:40 -05002016 SpvId typeId = this->getPointerType(type, get_storage_class(*swizzle.base()));
John Stiles9ce80f72021-03-11 22:35:19 -05002017 IntLiteral index(/*offset=*/-1, swizzle.components()[0],
2018 fContext.fTypes.fInt.get());
John Stilesb5db4822021-01-21 13:04:40 -05002019 SpvId indexId = this->writeIntLiteral(index);
2020 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002021 return std::make_unique<PointerLValue>(*this,
2022 member,
2023 /*isMemoryObjectPointer=*/false,
2024 this->getType(type),
John Stiles5570c512020-11-19 17:58:07 -05002025 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002026 } else {
John Stiles5570c512020-11-19 17:58:07 -05002027 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002028 swizzle.base()->type(), type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002029 }
2030 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002031 default: {
Kevin Lubickbe03ef12021-06-16 15:28:00 -04002032 // expr isn't actually an lvalue, create a placeholder variable for it. This case
2033 // happens due to the need to store values in temporary variables during function
2034 // calls (see comments in getFunctionType); erroneous uses of rvalues as lvalues
2035 // should have been caught by IRGenerator
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002036 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002037 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
2038 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07002039 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002040 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002041 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
2042 this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002043 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002044 }
2045}
2046
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002047SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002048 if (ref.variable()->modifiers().fLayout.fBuiltin == DEVICE_FRAGCOORDS_BUILTIN) {
2049 // Down below, we rewrite raw references to sk_FragCoord with expressions that reference
2050 // DEVICE_FRAGCOORDS_BUILTIN. This is a fake variable that means we need to directly access
2051 // the fragcoord; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002052 dsl::DSLGlobalVar fragCoord("sk_FragCoord");
Brian Salomond8d85b92021-07-07 09:41:17 -04002053 return this->getLValue(*dsl::DSLExpression(fragCoord).release(), out)->load(out);
2054 }
2055 if (ref.variable()->modifiers().fLayout.fBuiltin == DEVICE_CLOCKWISE_BUILTIN) {
2056 // Down below, we rewrite raw references to sk_Clockwise with expressions that reference
2057 // DEVICE_CLOCKWISE_BUILTIN. This is a fake variable that means we need to directly
2058 // access front facing; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002059 dsl::DSLGlobalVar clockwise("sk_Clockwise");
Brian Salomond8d85b92021-07-07 09:41:17 -04002060 return this->getLValue(*dsl::DSLExpression(clockwise).release(), out)->load(out);
2061 }
John Stilese40d1662021-01-29 10:08:50 -05002062
Brian Salomond8d85b92021-07-07 09:41:17 -04002063 // Handle inserting use of uniform to flip y when referencing sk_FragCoord.
John Stiles1e1fe122021-01-29 12:18:46 -05002064 const Variable* variable = ref.variable();
Brian Salomond8d85b92021-07-07 09:41:17 -04002065 if (variable->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
2066 this->addRTFlipUniform(ref.fOffset);
2067 // Use sk_RTAdjust to compute the flipped coordinate
2068 using namespace dsl;
2069 const char* DEVICE_COORDS_NAME = "__device_FragCoords";
2070 SymbolTable& symbols = *dsl::DSLWriter::SymbolTable();
2071 // Use a uniform to flip the Y coordinate. The new expression will be written in
2072 // terms of __device_FragCoords, which is a fake variable that means "access the
2073 // underlying fragcoords directly without flipping it".
2074 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
2075 SKSL_RTFLIP_NAME));
2076 if (!symbols[DEVICE_COORDS_NAME]) {
2077 Modifiers modifiers;
2078 modifiers.fLayout.fBuiltin = DEVICE_FRAGCOORDS_BUILTIN;
2079 if (fProgram.fPool) {
2080 fProgram.fPool->attachToThread();
Brian Salomon943108b02021-07-01 10:26:49 -04002081 }
John Stilesd7437ee2021-08-02 11:56:16 -04002082 auto coordsVar = std::make_unique<Variable>(/*offset=*/-1,
2083 fContext.fModifiersPool->add(modifiers),
2084 DEVICE_COORDS_NAME,
2085 fContext.fTypes.fFloat4.get(),
2086 true,
2087 Variable::Storage::kGlobal);
2088 fSPIRVBonusVariables.insert(coordsVar.get());
2089 symbols.add(std::move(coordsVar));
Brian Salomond8d85b92021-07-07 09:41:17 -04002090 if (fProgram.fPool) {
2091 fProgram.fPool->detachFromThread();
2092 }
Greg Daniela85e4bf2020-06-17 16:32:45 -04002093 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002094 DSLGlobalVar deviceCoord(DEVICE_COORDS_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002095 std::unique_ptr<Expression> rtFlipSkSLExpr = rtFlip.release();
2096 DSLExpression x = DSLExpression(rtFlipSkSLExpr->clone()).x();
2097 DSLExpression y = DSLExpression(std::move(rtFlipSkSLExpr)).y();
2098 return this->writeExpression(*dsl::Float4(deviceCoord.x(),
2099 std::move(x) + std::move(y) * deviceCoord.y(),
2100 deviceCoord.z(),
2101 deviceCoord.w()).release(),
2102 out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002103 }
John Stiles1e1fe122021-01-29 12:18:46 -05002104
Brian Salomond8d85b92021-07-07 09:41:17 -04002105 // Handle flipping sk_Clockwise.
2106 if (variable->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN) {
2107 this->addRTFlipUniform(ref.fOffset);
2108 using namespace dsl;
2109 const char* DEVICE_CLOCKWISE_NAME = "__device_Clockwise";
2110 SymbolTable& symbols = *dsl::DSLWriter::SymbolTable();
2111 // Use a uniform to flip the Y coordinate. The new expression will be written in
2112 // terms of __device_Clockwise, which is a fake variable that means "access the
2113 // underlying FrontFacing directly".
2114 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
2115 SKSL_RTFLIP_NAME));
2116 if (!symbols[DEVICE_CLOCKWISE_NAME]) {
2117 Modifiers modifiers;
2118 modifiers.fLayout.fBuiltin = DEVICE_CLOCKWISE_BUILTIN;
2119 if (fProgram.fPool) {
2120 fProgram.fPool->attachToThread();
2121 }
John Stilesd7437ee2021-08-02 11:56:16 -04002122 auto clockwiseVar = std::make_unique<Variable>(/*offset=*/-1,
2123 fContext.fModifiersPool->add(modifiers),
2124 DEVICE_CLOCKWISE_NAME,
2125 fContext.fTypes.fBool.get(),
2126 true,
2127 Variable::Storage::kGlobal);
2128 fSPIRVBonusVariables.insert(clockwiseVar.get());
2129 symbols.add(std::move(clockwiseVar));
Brian Salomond8d85b92021-07-07 09:41:17 -04002130 if (fProgram.fPool) {
2131 fProgram.fPool->detachFromThread();
2132 }
2133 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002134 DSLGlobalVar deviceClockwise(DEVICE_CLOCKWISE_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002135 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia,
2136 // we use the default convention of "counter-clockwise face is front".
2137 return this->writeExpression(*dsl::Bool(Select(rtFlip.y() > 0,
2138 !deviceClockwise,
2139 deviceClockwise)).release(),
2140 out);
Chris Daltonb91c4662018-08-01 10:46:22 -06002141 }
John Stiles1e1fe122021-01-29 12:18:46 -05002142
Brian Salomond8d85b92021-07-07 09:41:17 -04002143 return this->getLValue(ref, out)->load(out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002144}
2145
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002146SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002147 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002148 SpvId base = this->writeExpression(*expr.base(), out);
2149 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002150 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002151 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002152 index, out);
2153 return result;
2154 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002155 return getLValue(expr, out)->load(out);
2156}
2157
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002158SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002159 return getLValue(f, out)->load(out);
2160}
2161
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002162SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002163 SpvId base = this->writeExpression(*swizzle.base(), out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002164 SpvId result = this->nextId(&swizzle.type());
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002165 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002166 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002167 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002168 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002169 } else {
2170 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002171 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002172 this->writeWord(result, out);
2173 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002174 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002175 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002176 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002177 }
2178 }
2179 return result;
2180}
2181
Greg Daniel64773e62016-11-22 09:44:03 -05002182SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2183 const Type& operandType, SpvId lhs,
2184 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002185 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002186 SpvId result = this->nextId(&resultType);
ethannicholasd598f792016-07-25 10:08:54 -07002187 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002188 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002189 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002190 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002191 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002192 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002193 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002194 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2195 } else {
John Stiles123501f2020-12-09 10:08:13 -05002196 fErrors.error(operandType.fOffset,
2197 "unsupported operand for binary expression: " + operandType.description());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002198 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002199 return result;
2200}
2201
Ethan Nicholas48e24052018-03-14 13:51:39 -04002202SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2203 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002204 if (operandType.isVector()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002205 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002206 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002207 return result;
2208 }
2209 return id;
2210}
2211
Ethan Nicholas68990be2017-07-13 09:36:52 -04002212SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2213 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002214 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002215 OutputStream& out) {
2216 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002217 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002218 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2219 operandType.rows(),
2220 1));
John Stiles54e7c052021-01-11 14:22:36 -05002221 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002222 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002223 1));
John Stiles54e7c052021-01-11 14:22:36 -05002224 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002225 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002226 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002227 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002228 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002229 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002230 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002231 SpvId compare = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002232 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002233 SpvId merge = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002234 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002235 if (result != 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002236 SpvId next = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002237 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002238 result = next;
2239 }
2240 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002241 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002242 }
2243 }
2244 return result;
2245}
2246
Ethan Nicholas0df21132018-07-10 09:37:51 -04002247SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
John Stiles43b593c2021-05-13 22:03:27 -04002248 SpvId rhs, SpvOp_ op, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002249 SkASSERT(operandType.isMatrix());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002250 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2251 operandType.rows(),
2252 1));
John Stiles43b593c2021-05-13 22:03:27 -04002253 std::vector<SpvId> columns;
2254 columns.reserve(operandType.columns());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002255 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002256 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002257 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002258 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002259 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
John Stiles43b593c2021-05-13 22:03:27 -04002260 columns.push_back(this->nextId(&operandType));
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002261 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002262 }
John Stiles43b593c2021-05-13 22:03:27 -04002263 return this->writeComposite(columns, operandType, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002264}
2265
John Stiles9485b552021-01-27 11:47:00 -05002266static std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002267 if (type.isInteger()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002268 return IntLiteral::Make(/*offset=*/-1, /*value=*/1, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002269 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002270 else if (type.isFloat()) {
John Stiles9ce80f72021-03-11 22:35:19 -05002271 return FloatLiteral::Make(/*offset=*/-1, /*value=*/1.0, &type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002272 } else {
John Stilesf57207b2021-02-02 17:50:34 -05002273 SK_ABORT("math is unsupported on type '%s'", String(type.name()).c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -07002274 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002275}
2276
John Stilesd94bfdd2021-03-25 11:44:08 -04002277SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, OutputStream& out) {
2278 SkASSERT(type.isFloat());
2279 SpvId one = this->writeFloatLiteral({/*offset=*/-1, /*value=*/1, &type});
2280 SpvId reciprocal = this->nextId(&type);
2281 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
2282 return reciprocal;
2283}
2284
John Stilesa91bf052021-05-17 09:34:03 -04002285SpvId SPIRVCodeGenerator::writeScalarToMatrixSplat(const Type& matrixType,
2286 SpvId scalarId,
2287 OutputStream& out) {
2288 // Splat the scalar into a vector.
2289 const Type& vectorType = matrixType.componentType().toCompound(fContext,
2290 /*columns=*/matrixType.rows(),
2291 /*rows=*/1);
2292 std::vector<SpvId> vecArguments(/*count*/ matrixType.rows(), /*value*/ scalarId);
2293 SpvId vectorId = this->writeComposite(vecArguments, vectorType, out);
2294
2295 // Splat the vector into a matrix.
2296 std::vector<SpvId> matArguments(/*count*/ matrixType.columns(), /*value*/ vectorId);
2297 return this->writeComposite(matArguments, matrixType, out);
2298}
2299
John Stiles45990502021-02-16 10:55:27 -05002300SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
Ethan Nicholas49465b42019-04-17 12:22:21 -04002301 const Type& rightType, SpvId rhs,
2302 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002303 // The comma operator ignores the type of the left-hand side entirely.
John Stiles45990502021-02-16 10:55:27 -05002304 if (op.kind() == Token::Kind::TK_COMMA) {
John Stilesd0614f22020-12-09 11:11:41 -05002305 return rhs;
2306 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002307 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002308 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002309 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2310 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002311 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002312 if (leftType.isVector() && rightType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002313 if (resultType.componentType().isFloat()) {
2314 switch (op.kind()) {
2315 case Token::Kind::TK_SLASH: {
2316 rhs = this->writeReciprocal(rightType, rhs, out);
2317 [[fallthrough]];
2318 }
2319 case Token::Kind::TK_STAR: {
2320 SpvId result = this->nextId(&resultType);
2321 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2322 result, lhs, rhs, out);
2323 return result;
2324 }
2325 default:
2326 break;
2327 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002328 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002329 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002330 const Type& vecType = leftType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002331 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002332 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2333 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002334 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002335 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002336 this->writeWord(rhs, out);
2337 }
2338 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002339 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002340 } else if (rightType.isVector() && leftType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002341 if (resultType.componentType().isFloat()) {
2342 if (op.kind() == Token::Kind::TK_STAR) {
2343 SpvId result = this->nextId(&resultType);
2344 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2345 result, rhs, lhs, out);
2346 return result;
2347 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002348 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002349 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002350 const Type& vecType = rightType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002351 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002352 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2353 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002354 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002355 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002356 this->writeWord(lhs, out);
2357 }
2358 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002359 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002360 } else if (leftType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002361 if (op.kind() == Token::Kind::TK_STAR) {
2362 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2363 SpvOp_ spvop;
2364 if (rightType.isMatrix()) {
2365 spvop = SpvOpMatrixTimesMatrix;
2366 } else if (rightType.isVector()) {
2367 spvop = SpvOpMatrixTimesVector;
2368 } else {
2369 SkASSERT(rightType.isScalar());
2370 spvop = SpvOpMatrixTimesScalar;
2371 }
2372 SpvId result = this->nextId(&resultType);
2373 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
2374 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002375 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002376 // Matrix-op-vector is not supported in GLSL/SkSL for non-multiplication ops; we
2377 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002378 SkASSERT(rightType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002379
2380 // Splat rhs across an entire matrix so we can reuse the matrix-op-matrix path.
2381 SpvId rhsMatrix = this->writeScalarToMatrixSplat(leftType, rhs, out);
2382
2383 // Perform this operation as matrix-op-matrix.
2384 return this->writeBinaryExpression(leftType, lhs, op, leftType, rhsMatrix,
2385 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002386 }
John Stiles9aeed132020-11-24 17:36:06 -05002387 } else if (rightType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002388 if (op.kind() == Token::Kind::TK_STAR) {
2389 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2390 SpvId result = this->nextId(&resultType);
2391 if (leftType.isVector()) {
2392 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType),
2393 result, lhs, rhs, out);
2394 } else {
2395 SkASSERT(leftType.isScalar());
2396 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType),
2397 result, rhs, lhs, out);
2398 }
2399 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002400 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002401 // Vector-op-matrix is not supported in GLSL/SkSL for non-multiplication ops; we
2402 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002403 SkASSERT(leftType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002404
2405 // Splat lhs across an entire matrix so we can reuse the matrix-op-matrix path.
2406 SpvId lhsMatrix = this->writeScalarToMatrixSplat(rightType, lhs, out);
2407
2408 // Perform this operation as matrix-op-matrix.
2409 return this->writeBinaryExpression(rightType, lhsMatrix, op, rightType, rhs,
2410 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002411 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002412 } else {
John Stilesd8ca6b62020-11-23 14:28:36 -05002413 fErrors.error(leftType.fOffset, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002414 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002415 }
2416 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002417 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002418 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002419 }
John Stiles45990502021-02-16 10:55:27 -05002420 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002421 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002422 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002423 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002424 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002425 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002426 if (operandType->isStruct()) {
2427 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2428 }
John Stiles35092102021-04-08 23:30:51 -04002429 if (operandType->isArray()) {
2430 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2431 }
John Stiles4a7dc462020-11-25 11:08:08 -05002432 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002433 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002434 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002435 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2436 operandType->columns(),
2437 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002438 } else {
2439 tmpType = &resultType;
2440 }
2441 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002442 SpvOpFOrdEqual, SpvOpIEqual,
2443 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002444 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002445 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002446 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002447 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002448 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002449 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002450 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002451 if (operandType->isStruct()) {
2452 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2453 }
John Stiles35092102021-04-08 23:30:51 -04002454 if (operandType->isArray()) {
2455 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2456 }
John Stiles4a7dc462020-11-25 11:08:08 -05002457 [[fallthrough]];
2458 case Token::Kind::TK_LOGICALXOR:
2459 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002460 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002461 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002462 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2463 operandType->columns(),
2464 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002465 } else {
2466 tmpType = &resultType;
2467 }
2468 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002469 SpvOpFOrdNotEqual, SpvOpINotEqual,
2470 SpvOpINotEqual, SpvOpLogicalNotEqual,
2471 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002472 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002473 case Token::Kind::TK_GT:
John Stiles4a7dc462020-11-25 11:08:08 -05002474 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002475 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2476 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002477 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002478 case Token::Kind::TK_LT:
John Stiles4a7dc462020-11-25 11:08:08 -05002479 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002480 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002481 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002482 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002483 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002484 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2485 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002486 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002487 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002488 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002489 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2490 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002491 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002492 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002493 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002494 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002495 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFAdd, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002496 }
Greg Daniel64773e62016-11-22 09:44:03 -05002497 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002498 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002499 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002500 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002501 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002502 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFSub, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002503 }
Greg Daniel64773e62016-11-22 09:44:03 -05002504 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002505 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002506 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002507 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002508 // matrix multiply
Ethan Nicholas7f015882021-03-23 14:16:52 -04002509 SpvId result = this->nextId(&resultType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002510 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2511 lhs, rhs, out);
2512 return result;
2513 }
Greg Daniel64773e62016-11-22 09:44:03 -05002514 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002515 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002516 case Token::Kind::TK_SLASH:
John Stilesbdf3bb72021-05-17 09:34:23 -04002517 if (leftType.isMatrix() && rightType.isMatrix()) {
2518 SkASSERT(leftType == rightType);
2519 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFDiv, out);
2520 }
Greg Daniel64773e62016-11-22 09:44:03 -05002521 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002522 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002523 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002524 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2525 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002526 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002527 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2528 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2529 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002530 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002531 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2532 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2533 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002534 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002535 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2536 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002537 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002538 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2539 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002540 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002541 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2542 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002543 default:
John Stiles5570c512020-11-19 17:58:07 -05002544 fErrors.error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002545 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002546 }
2547}
2548
John Stiles35092102021-04-08 23:30:51 -04002549SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
2550 SpvId rhs, OutputStream& out) {
2551 // The inputs must be arrays, and the op must be == or !=.
2552 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
2553 SkASSERT(arrayType.isArray());
2554 const Type& componentType = arrayType.componentType();
2555 const SpvId componentTypeId = this->getType(componentType);
2556 const int arraySize = arrayType.columns();
2557 SkASSERT(arraySize > 0);
2558
2559 // Synthesize equality checks for each item in the array.
2560 const Type& boolType = *fContext.fTypes.fBool;
2561 SpvId allComparisons = (SpvId)-1;
2562 for (int index = 0; index < arraySize; ++index) {
2563 // Get the left and right item in the array.
2564 SpvId itemL = this->nextId(&componentType);
2565 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemL, lhs, index, out);
2566 SpvId itemR = this->nextId(&componentType);
2567 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemR, rhs, index, out);
2568 // Use `writeBinaryExpression` with the requested == or != operator on these items.
2569 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
2570 componentType, itemR, boolType, out);
2571 // Merge this comparison result with all the other comparisons we've done.
2572 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
2573 }
2574 return allComparisons;
2575}
2576
John Stilesbc5c2a02021-04-08 11:44:53 -04002577SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
2578 SpvId rhs, OutputStream& out) {
2579 // The inputs must be structs containing fields, and the op must be == or !=.
John Stilesbc5c2a02021-04-08 11:44:53 -04002580 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
John Stiles35092102021-04-08 23:30:51 -04002581 SkASSERT(structType.isStruct());
John Stilesbc5c2a02021-04-08 11:44:53 -04002582 const std::vector<Type::Field>& fields = structType.fields();
2583 SkASSERT(!fields.empty());
2584
2585 // Synthesize equality checks for each field in the struct.
2586 const Type& boolType = *fContext.fTypes.fBool;
John Stilesbc5c2a02021-04-08 11:44:53 -04002587 SpvId allComparisons = (SpvId)-1;
2588 for (int index = 0; index < (int)fields.size(); ++index) {
2589 // Get the left and right versions of this field.
2590 const Type& fieldType = *fields[index].fType;
John Stiles35092102021-04-08 23:30:51 -04002591 const SpvId fieldTypeId = this->getType(fieldType);
John Stilesbc5c2a02021-04-08 11:44:53 -04002592
2593 SpvId fieldL = this->nextId(&fieldType);
2594 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldL, lhs, index, out);
2595 SpvId fieldR = this->nextId(&fieldType);
2596 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldR, rhs, index, out);
2597 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
2598 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
2599 boolType, out);
John Stiles35092102021-04-08 23:30:51 -04002600 // Merge this comparison result with all the other comparisons we've done.
2601 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002602 }
2603 return allComparisons;
2604}
2605
John Stiles35092102021-04-08 23:30:51 -04002606SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
2607 OutputStream& out) {
2608 // If this is the first entry, we don't need to merge comparison results with anything.
2609 if (allComparisons == (SpvId)-1) {
2610 return comparison;
2611 }
2612 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
2613 const Type& boolType = *fContext.fTypes.fBool;
2614 SpvId boolTypeId = this->getType(boolType);
2615 SpvId logicalOp = this->nextId(&boolType);
2616 switch (op.kind()) {
2617 case Token::Kind::TK_EQEQ:
2618 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
2619 comparison, allComparisons, out);
2620 break;
2621 case Token::Kind::TK_NEQ:
2622 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
2623 comparison, allComparisons, out);
2624 break;
2625 default:
2626 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
2627 return (SpvId)-1;
2628 }
2629 return logicalOp;
2630}
2631
John Stilesbc5c2a02021-04-08 11:44:53 -04002632static float division_by_literal_value(Operator op, const Expression& right) {
2633 // If this is a division by a literal value, returns that literal value. Otherwise, returns 0.
2634 if (op.kind() == Token::Kind::TK_SLASH && right.is<FloatLiteral>()) {
2635 float rhsValue = right.as<FloatLiteral>().value();
2636 if (std::isfinite(rhsValue)) {
2637 return rhsValue;
2638 }
2639 }
2640 return 0.0f;
2641}
2642
Ethan Nicholas49465b42019-04-17 12:22:21 -04002643SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2396fb82021-03-25 11:44:55 -04002644 const Expression* left = b.left().get();
2645 const Expression* right = b.right().get();
John Stiles45990502021-02-16 10:55:27 -05002646 Operator op = b.getOperator();
John Stilesbc5c2a02021-04-08 11:44:53 -04002647
John Stiles45990502021-02-16 10:55:27 -05002648 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002649 case Token::Kind::TK_EQ: {
John Stilesbc5c2a02021-04-08 11:44:53 -04002650 // Handles assignment.
John Stiles2396fb82021-03-25 11:44:55 -04002651 SpvId rhs = this->writeExpression(*right, out);
2652 this->getLValue(*left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002653 return rhs;
2654 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002655 case Token::Kind::TK_LOGICALAND:
John Stilesbc5c2a02021-04-08 11:44:53 -04002656 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2657 return this->writeLogicalAnd(*b.left(), *b.right(), out);
2658
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002659 case Token::Kind::TK_LOGICALOR:
John Stilesbc5c2a02021-04-08 11:44:53 -04002660 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2661 return this->writeLogicalOr(*b.left(), *b.right(), out);
2662
Ethan Nicholas49465b42019-04-17 12:22:21 -04002663 default:
2664 break;
2665 }
2666
2667 std::unique_ptr<LValue> lvalue;
2668 SpvId lhs;
John Stiles45990502021-02-16 10:55:27 -05002669 if (op.isAssignment()) {
John Stiles2396fb82021-03-25 11:44:55 -04002670 lvalue = this->getLValue(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002671 lhs = lvalue->load(out);
2672 } else {
2673 lvalue = nullptr;
John Stiles2396fb82021-03-25 11:44:55 -04002674 lhs = this->writeExpression(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002675 }
John Stiles2396fb82021-03-25 11:44:55 -04002676
John Stilesbc5c2a02021-04-08 11:44:53 -04002677 SpvId rhs;
2678 float rhsValue = division_by_literal_value(op, *right);
2679 if (rhsValue != 0.0f) {
2680 // Rewrite floating-point division by a literal into multiplication by the reciprocal.
2681 // This converts `expr / 2` into `expr * 0.5`
2682 // This improves codegen, especially for certain types of divides (e.g. vector/scalar).
2683 op = Operator(Token::Kind::TK_STAR);
2684 FloatLiteral reciprocal{right->fOffset, 1.0f / rhsValue, &right->type()};
2685 rhs = this->writeExpression(reciprocal, out);
2686 } else {
2687 // Write the right-hand side expression normally.
John Stiles2396fb82021-03-25 11:44:55 -04002688 rhs = this->writeExpression(*right, out);
2689 }
2690
2691 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
2692 right->type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002693 if (lvalue) {
2694 lvalue->store(result, out);
2695 }
2696 return result;
2697}
2698
John Stilesbc5c2a02021-04-08 11:44:53 -04002699SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
2700 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002701 BoolLiteral falseLiteral(/*offset=*/-1, /*value=*/false, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002702 SpvId falseConstant = this->writeBoolLiteral(falseLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002703 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002704 SpvId rhsLabel = this->nextId(nullptr);
2705 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002706 SpvId lhsBlock = fCurrentBlock;
2707 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2708 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2709 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002710 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002711 SpvId rhsBlock = fCurrentBlock;
2712 this->writeInstruction(SpvOpBranch, end, out);
2713 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002714 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002715 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002716 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002717 return result;
2718}
2719
John Stilesbc5c2a02021-04-08 11:44:53 -04002720SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
2721 OutputStream& out) {
John Stiles9ce80f72021-03-11 22:35:19 -05002722 BoolLiteral trueLiteral(/*offset=*/-1, /*value=*/true, fContext.fTypes.fBool.get());
ethannicholasb3058bd2016-07-01 08:22:01 -07002723 SpvId trueConstant = this->writeBoolLiteral(trueLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002724 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002725 SpvId rhsLabel = this->nextId(nullptr);
2726 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002727 SpvId lhsBlock = fCurrentBlock;
2728 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2729 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2730 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002731 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002732 SpvId rhsBlock = fCurrentBlock;
2733 this->writeInstruction(SpvOpBranch, end, out);
2734 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002735 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002736 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002737 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002738 return result;
2739}
2740
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002741SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002742 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002743 SpvId test = this->writeExpression(*t.test(), out);
2744 if (t.ifTrue()->type().columns() == 1 &&
2745 t.ifTrue()->isCompileTimeConstant() &&
2746 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002747 // both true and false are constants, can just use OpSelect
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002748 SpvId result = this->nextId(nullptr);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002749 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2750 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002751 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002752 out);
2753 return result;
2754 }
Greg Daniel64773e62016-11-22 09:44:03 -05002755 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002756 // Adreno. Switched to storing the result in a temp variable as glslang does.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002757 SpvId var = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002758 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002759 var, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002760 SpvId trueLabel = this->nextId(nullptr);
2761 SpvId falseLabel = this->nextId(nullptr);
2762 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002763 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2764 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2765 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002766 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002767 this->writeInstruction(SpvOpBranch, end, out);
2768 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002769 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002770 this->writeInstruction(SpvOpBranch, end, out);
2771 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002772 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002773 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002774 return result;
2775}
2776
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002777SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002778 const Type& type = p.type();
John Stiles45990502021-02-16 10:55:27 -05002779 if (p.getOperator().kind() == Token::Kind::TK_MINUS) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002780 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002781 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002782 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002783 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002784 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002785 } else if (is_signed(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002786 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2787 } else {
John Stileseada7bc2021-02-02 16:29:32 -05002788 SkDEBUGFAILF("unsupported prefix expression %s", p.description().c_str());
Brian Salomon23356442018-11-30 15:33:19 -05002789 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002790 return result;
2791 }
John Stiles45990502021-02-16 10:55:27 -05002792 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002793 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002794 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002795 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002796 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002797 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2798 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one,
Greg Daniel64773e62016-11-22 09:44:03 -05002799 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002800 out);
2801 lv->store(result, out);
2802 return result;
2803 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002804 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002805 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002806 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2807 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2808 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002809 lv->store(result, out);
2810 return result;
2811 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002812 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002813 SkASSERT(p.operand()->type().isBoolean());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002814 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002815 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2816 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002817 return result;
2818 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002819 case Token::Kind::TK_BITWISENOT: {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002820 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002821 this->writeInstruction(SpvOpNot, this->getType(type), result,
2822 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002823 return result;
2824 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002825 default:
John Stileseada7bc2021-02-02 16:29:32 -05002826 SkDEBUGFAILF("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002827 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002828 }
2829}
2830
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002831SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002832 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002833 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002834 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002835 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
John Stiles45990502021-02-16 10:55:27 -05002836 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002837 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002838 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002839 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2840 lv->store(temp, out);
2841 return result;
2842 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002843 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002844 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002845 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2846 lv->store(temp, out);
2847 return result;
2848 }
2849 default:
John Stileseada7bc2021-02-02 16:29:32 -05002850 SkDEBUGFAILF("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002851 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002852 }
2853}
2854
ethannicholasf789b382016-08-03 12:43:36 -07002855SpvId SPIRVCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04002856 if (b.value()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002857 if (fBoolTrue == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002858 fBoolTrue = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002859 this->writeInstruction(SpvOpConstantTrue, this->getType(b.type()), fBoolTrue,
ethannicholasb3058bd2016-07-01 08:22:01 -07002860 fConstantBuffer);
2861 }
2862 return fBoolTrue;
2863 } else {
2864 if (fBoolFalse == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002865 fBoolFalse = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002866 this->writeInstruction(SpvOpConstantFalse, this->getType(b.type()), fBoolFalse,
ethannicholasb3058bd2016-07-01 08:22:01 -07002867 fConstantBuffer);
2868 }
2869 return fBoolFalse;
2870 }
2871}
2872
ethannicholasf789b382016-08-03 12:43:36 -07002873SpvId SPIRVCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002874 SPIRVNumberConstant key{i.value(), i.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002875 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2876 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002877 SpvId result = this->nextId(nullptr);
John Stilesacb091f2021-01-06 11:57:58 -05002878 this->writeInstruction(SpvOpConstant, this->getType(i.type()), result, (SpvId) i.value(),
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002879 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002880 iter->second = result;
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04002881 }
John Stilesacb091f2021-01-06 11:57:58 -05002882 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002883}
2884
ethannicholasf789b382016-08-03 12:43:36 -07002885SpvId SPIRVCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
John Stilesbdc3d3c2021-01-06 18:41:40 -05002886 // Convert the float literal into its bit-representation.
2887 float value = f.value();
2888 uint32_t valueBits;
2889 static_assert(sizeof(valueBits) == sizeof(value));
2890 memcpy(&valueBits, &value, sizeof(value));
2891
2892 SPIRVNumberConstant key{valueBits, f.type().numberKind()};
John Stilesacb091f2021-01-06 11:57:58 -05002893 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2894 if (newlyCreated) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002895 SpvId result = this->nextId(nullptr);
John Stilesbdc3d3c2021-01-06 18:41:40 -05002896 this->writeInstruction(SpvOpConstant, this->getType(f.type()), result, (SpvId) valueBits,
John Stiles8c578662020-06-01 15:32:47 +00002897 fConstantBuffer);
John Stilesacb091f2021-01-06 11:57:58 -05002898 iter->second = result;
John Stiles8c578662020-06-01 15:32:47 +00002899 }
John Stilesacb091f2021-01-06 11:57:58 -05002900 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002901}
2902
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002903SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002904 SpvId result = fFunctionMap[&f];
John Stilesb5db4822021-01-21 13:04:40 -05002905 SpvId returnTypeId = this->getType(f.returnType());
2906 SpvId functionTypeId = this->getFunctionType(f);
2907 this->writeInstruction(SpvOpFunction, returnTypeId, result,
2908 SpvFunctionControlMaskNone, functionTypeId, out);
John Stilesf9e85512021-03-22 12:05:31 -04002909 String mangledName = f.mangledName();
2910 this->writeInstruction(SpvOpName,
2911 result,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002912 skstd::string_view(mangledName.c_str(), mangledName.size()),
John Stilesf9e85512021-03-22 12:05:31 -04002913 fNameBuffer);
2914 for (const Variable* parameter : f.parameters()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002915 SpvId id = this->nextId(nullptr);
John Stilesf9e85512021-03-22 12:05:31 -04002916 fVariableMap[parameter] = id;
2917 SpvId type = this->getPointerType(parameter->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002918 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2919 }
2920 return result;
2921}
2922
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002923SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2924 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002925 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002926 fCurrentBlock = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002927 this->writeLabel(this->nextId(nullptr), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002928 StringStream bodyBuffer;
John Stiles0693fb82021-01-22 18:27:52 -05002929 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002930 write_stringstream(fVariableBuffer, out);
John Stilese8da4d22021-03-24 09:19:45 -04002931 if (f.declaration().isMain()) {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002932 write_stringstream(fGlobalInitializersBuffer, out);
2933 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002934 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002935 if (fCurrentBlock) {
John Stiles2558c462021-03-16 17:49:20 -04002936 if (f.declaration().returnType().isVoid()) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002937 this->writeInstruction(SpvOpReturn, out);
2938 } else {
2939 this->writeInstruction(SpvOpUnreachable, out);
2940 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002941 }
2942 this->writeInstruction(SpvOpFunctionEnd, out);
2943 return result;
2944}
2945
2946void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2947 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002948 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002949 fDecorationBuffer);
2950 }
2951 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002952 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002953 fDecorationBuffer);
2954 }
2955 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002956 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002957 fDecorationBuffer);
2958 }
2959 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002960 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002961 fDecorationBuffer);
2962 }
Greg Daniel64773e62016-11-22 09:44:03 -05002963 if (layout.fInputAttachmentIndex >= 0) {
2964 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2965 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002966 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002967 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04002968 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN &&
Greg Daniele6ab9982018-08-22 13:56:32 +00002969 layout.fBuiltin != SK_IN_BUILTIN && layout.fBuiltin != SK_OUT_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002970 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002971 fDecorationBuffer);
2972 }
2973}
2974
2975void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2976 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002977 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002978 layout.fLocation, fDecorationBuffer);
2979 }
2980 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002981 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002982 layout.fBinding, fDecorationBuffer);
2983 }
2984 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002985 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002986 layout.fIndex, fDecorationBuffer);
2987 }
2988 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002989 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002990 layout.fSet, fDecorationBuffer);
2991 }
Greg Daniel64773e62016-11-22 09:44:03 -05002992 if (layout.fInputAttachmentIndex >= 0) {
2993 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
2994 layout.fInputAttachmentIndex, fDecorationBuffer);
2995 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002996 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002997 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07002998 layout.fBuiltin, fDecorationBuffer);
2999 }
3000}
3001
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003002MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003003 bool pushConstant = ((v.modifiers().fLayout.fFlags & Layout::kPushConstant_Flag) != 0);
Brian Osman58ee8982021-02-18 15:39:38 -05003004 return pushConstant ? MemoryLayout(MemoryLayout::k430_Standard) : fDefaultLayout;
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003005}
3006
Ethan Nicholas81d15112018-07-13 12:48:50 -04003007static void update_sk_in_count(const Modifiers& m, int* outSkInCount) {
3008 switch (m.fLayout.fPrimitive) {
3009 case Layout::kPoints_Primitive:
3010 *outSkInCount = 1;
3011 break;
3012 case Layout::kLines_Primitive:
3013 *outSkInCount = 2;
3014 break;
3015 case Layout::kLinesAdjacency_Primitive:
3016 *outSkInCount = 4;
3017 break;
3018 case Layout::kTriangles_Primitive:
3019 *outSkInCount = 3;
3020 break;
3021 case Layout::kTrianglesAdjacency_Primitive:
3022 *outSkInCount = 6;
3023 break;
3024 default:
3025 return;
3026 }
3027}
3028
Brian Salomond8d85b92021-07-07 09:41:17 -04003029SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTFlip) {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003030 MemoryLayout memoryLayout = this->memoryLayoutForVariable(intf.variable());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003031 SpvId result = this->nextId(nullptr);
Brian Salomond8d85b92021-07-07 09:41:17 -04003032 const Variable& intfVar = intf.variable();
3033 const Type& type = intfVar.type();
3034 if (!MemoryLayout::LayoutIsSupported(type)) {
3035 fErrors.error(type.fOffset, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003036 return this->nextId(nullptr);
John Stiles0023c0c2020-11-16 13:32:18 -05003037 }
John Stiles9485b552021-01-27 11:47:00 -05003038 SpvStorageClass_ storageClass = get_storage_class(intf.variable(), SpvStorageClassFunction);
Brian Salomond8d85b92021-07-07 09:41:17 -04003039 if (fProgram.fInputs.fUseFlipRTUniform && appendRTFlip) {
3040 // We can only have one interface block (because we use push_constant and that is limited
3041 // to one per program), so we need to append rtflip to this one rather than synthesize an
3042 // entirely new block when the variable is referenced. And we can't modify the existing
3043 // block, so we instead create a modified copy of it and write that.
3044 std::vector<Type::Field> fields = type.fields();
3045 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3046 /*location=*/-1,
3047 fProgram.fConfig->fSettings.fRTFlipOffset,
3048 /*binding=*/-1,
3049 /*index=*/-1,
3050 /*set=*/-1,
3051 /*builtin=*/-1,
3052 /*inputAttachmentIndex=*/-1,
3053 Layout::kUnspecified_Primitive,
3054 /*maxVertices=*/1,
Brian Osman8c264792021-07-01 16:41:27 -04003055 /*invocations=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003056 /*flags=*/0),
3057 SKSL_RTFLIP_NAME,
3058 fContext.fTypes.fFloat2.get());
3059 if (fProgram.fPool) {
3060 fProgram.fPool->attachToThread();
3061 }
3062 const Type* rtFlipStructType = fProgram.fSymbols->takeOwnershipOfSymbol(
Ethan Nicholas27f06eb2021-07-26 16:39:40 -04003063 Type::MakeStructType(type.fOffset, type.name(), std::move(fields)));
Brian Salomond8d85b92021-07-07 09:41:17 -04003064 const Variable* modifiedVar = fProgram.fSymbols->takeOwnershipOfSymbol(
3065 std::make_unique<Variable>(intfVar.fOffset,
3066 &intfVar.modifiers(),
3067 intfVar.name(),
3068 rtFlipStructType,
3069 intfVar.isBuiltin(),
3070 intfVar.storage()));
John Stilesd7437ee2021-08-02 11:56:16 -04003071 fSPIRVBonusVariables.insert(modifiedVar);
Brian Salomond8d85b92021-07-07 09:41:17 -04003072 InterfaceBlock modifiedCopy(intf.fOffset,
3073 modifiedVar,
3074 intf.typeName(),
3075 intf.instanceName(),
3076 intf.arraySize(),
3077 intf.typeOwner());
3078 SpvId result = this->writeInterfaceBlock(modifiedCopy, false);
3079 fProgram.fSymbols->add(std::make_unique<Field>(
3080 /*offset=*/-1, modifiedVar, rtFlipStructType->fields().size() - 1));
3081 if (fProgram.fPool) {
3082 fProgram.fPool->detachFromThread();
3083 }
3084 fVariableMap[&intfVar] = result;
3085 fWroteRTFlip = true;
3086 return result;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003087 }
Ethan Nicholas5226b772018-05-03 16:20:41 -04003088 SpvId typeId;
Brian Salomond8d85b92021-07-07 09:41:17 -04003089 const Modifiers& intfModifiers = intfVar.modifiers();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003090 if (intfModifiers.fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osman133724c2020-10-28 14:14:39 -04003091 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003092 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003093 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholas81d15112018-07-13 12:48:50 -04003094 update_sk_in_count(m, &fSkInCount);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003095 }
3096 }
Brian Salomond8d85b92021-07-07 09:41:17 -04003097 typeId = this->getType(*Type::MakeArrayType("sk_in", type.componentType(), fSkInCount),
3098 memoryLayout);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003099 } else {
Brian Salomond8d85b92021-07-07 09:41:17 -04003100 typeId = this->getType(type, memoryLayout);
Ethan Nicholas5226b772018-05-03 16:20:41 -04003101 }
Brian Osman58ee8982021-02-18 15:39:38 -05003102 if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00003103 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04003104 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003105 SpvId ptrType = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003106 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003107 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003108 Layout layout = intfModifiers.fLayout;
3109 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04003110 layout.fSet = 0;
3111 }
3112 this->writeLayout(layout, result);
Brian Salomond8d85b92021-07-07 09:41:17 -04003113 fVariableMap[&intfVar] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07003114 return result;
3115}
3116
John Stilesd7437ee2021-08-02 11:56:16 -04003117bool SPIRVCodeGenerator::isDead(const Variable& var) const {
3118 // During SPIR-V code generation, we synthesize some extra bonus variables that don't actually
3119 // exist in the Program at all and aren't tracked by the ProgramUsage. They aren't dead, though.
3120 if (fSPIRVBonusVariables.count(&var)) {
3121 return false;
3122 }
3123 ProgramUsage::VariableCounts counts = fProgram.usage()->get(var);
Brian Osman010ce6a2020-10-19 16:34:10 -04003124 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07003125 return false;
3126 }
Brian Osmand1f3b972021-03-22 17:03:42 -04003127 // It's not entirely clear what the rules are for eliding interface variables. Generally, it
3128 // causes problems to elide them, even when they're dead.
3129 return !(var.modifiers().fFlags &
3130 (Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag));
Chris Dalton2284aab2019-11-15 11:02:24 -07003131}
3132
John Stilesdbd4e6f2021-02-16 13:29:15 -05003133void SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind, const VarDeclaration& varDecl) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003134 const Variable& var = varDecl.var();
John Stiles0ca2f592021-01-27 10:58:10 -05003135 // 9999 is a sentinel value used in our built-in modules that causes us to ignore these
3136 // declarations, beyond adding them to the symbol table.
3137 constexpr int kBuiltinIgnore = 9999;
3138 if (var.modifiers().fLayout.fBuiltin == kBuiltinIgnore) {
Brian Osmanc0213602020-10-06 14:43:32 -04003139 return;
3140 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003141 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
John Stilesdbd4e6f2021-02-16 13:29:15 -05003142 kind != ProgramKind::kFragment) {
John Stiles270cec22021-02-17 12:59:36 -05003143 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Osmanc0213602020-10-06 14:43:32 -04003144 return;
3145 }
John Stilesd7437ee2021-08-02 11:56:16 -04003146 if (this->isDead(var)) {
Brian Osmanc0213602020-10-06 14:43:32 -04003147 return;
3148 }
John Stiles0de76f72021-01-29 09:19:39 -05003149 SpvStorageClass_ storageClass = get_storage_class(var, SpvStorageClassPrivate);
John Stilese40d1662021-01-29 10:08:50 -05003150 if (storageClass == SpvStorageClassUniform) {
3151 // Top-level uniforms are emitted in writeUniformBuffer.
3152 fTopLevelUniforms.push_back(&varDecl);
3153 return;
3154 }
3155 const Type& type = var.type();
John Stilesd8fc95d2021-01-26 16:22:53 -05003156 Layout layout = var.modifiers().fLayout;
John Stilese40d1662021-01-29 10:08:50 -05003157 if (layout.fSet < 0 && storageClass == SpvStorageClassUniformConstant) {
John Stiles270cec22021-02-17 12:59:36 -05003158 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
Brian Osmanc0213602020-10-06 14:43:32 -04003159 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003160 SpvId id = this->nextId(&type);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003161 fVariableMap[&var] = id;
Brian Osmanc0213602020-10-06 14:43:32 -04003162 SpvId typeId;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003163 if (var.modifiers().fLayout.fBuiltin == SK_IN_BUILTIN) {
Brian Osmanc0213602020-10-06 14:43:32 -04003164 typeId = this->getPointerType(
John Stilesad2d4942020-12-11 16:55:58 -05003165 *Type::MakeArrayType("sk_in", type.componentType(), fSkInCount),
Brian Osmanc0213602020-10-06 14:43:32 -04003166 storageClass);
3167 } else {
3168 typeId = this->getPointerType(type, storageClass);
3169 }
3170 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003171 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003172 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04003173 SkASSERT(!fCurrentBlock);
3174 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003175 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04003176 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
3177 fCurrentBlock = 0;
3178 }
John Stilesd8fc95d2021-01-26 16:22:53 -05003179 this->writeLayout(layout, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003180 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003181 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
3182 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003183 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003184 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
3185 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003186 }
3187}
3188
Brian Osmanc0213602020-10-06 14:43:32 -04003189void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003190 const Variable& var = varDecl.var();
Ethan Nicholas7f015882021-03-23 14:16:52 -04003191 SpvId id = this->nextId(&var.type());
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003192 fVariableMap[&var] = id;
3193 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04003194 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003195 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
3196 if (varDecl.value()) {
3197 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04003198 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003199 }
3200}
3201
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003202void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003203 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04003204 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04003205 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04003206 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003207 case Statement::Kind::kBlock:
John Stiles0693fb82021-01-22 18:27:52 -05003208 this->writeBlock(s.as<Block>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003209 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003210 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04003211 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003212 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003213 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04003214 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003215 break;
Brian Osmanc0213602020-10-06 14:43:32 -04003216 case Statement::Kind::kVarDeclaration:
3217 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003218 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003219 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04003220 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003221 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003222 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04003223 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003224 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003225 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04003226 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003227 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003228 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04003229 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003230 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003231 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07003232 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
3233 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003234 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07003235 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
3236 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003237 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07003238 this->writeInstruction(SpvOpKill, out);
3239 break;
3240 default:
John Stileseada7bc2021-02-02 16:29:32 -05003241 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003242 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003243 }
3244}
3245
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003246void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04003247 for (const std::unique_ptr<Statement>& stmt : b.children()) {
3248 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003249 }
3250}
3251
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003252void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003253 SpvId test = this->writeExpression(*stmt.test(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003254 SpvId ifTrue = this->nextId(nullptr);
3255 SpvId ifFalse = this->nextId(nullptr);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003256 if (stmt.ifFalse()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003257 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003258 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3259 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3260 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003261 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003262 if (fCurrentBlock) {
3263 this->writeInstruction(SpvOpBranch, end, out);
3264 }
3265 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003266 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003267 if (fCurrentBlock) {
3268 this->writeInstruction(SpvOpBranch, end, out);
3269 }
3270 this->writeLabel(end, out);
3271 } else {
3272 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3273 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3274 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003275 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003276 if (fCurrentBlock) {
3277 this->writeInstruction(SpvOpBranch, ifFalse, out);
3278 }
3279 this->writeLabel(ifFalse, out);
3280 }
3281}
3282
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003283void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003284 if (f.initializer()) {
3285 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003286 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003287 SpvId header = this->nextId(nullptr);
3288 SpvId start = this->nextId(nullptr);
3289 SpvId body = this->nextId(nullptr);
3290 SpvId next = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003291 fContinueTarget.push(next);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003292 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003293 fBreakTarget.push(end);
3294 this->writeInstruction(SpvOpBranch, header, out);
3295 this->writeLabel(header, out);
3296 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003297 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003298 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003299 if (f.test()) {
3300 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003301 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003302 } else {
3303 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003304 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003305 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003306 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003307 if (fCurrentBlock) {
3308 this->writeInstruction(SpvOpBranch, next, out);
3309 }
3310 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003311 if (f.next()) {
3312 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003313 }
3314 this->writeInstruction(SpvOpBranch, header, out);
3315 this->writeLabel(end, out);
3316 fBreakTarget.pop();
3317 fContinueTarget.pop();
3318}
3319
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003320void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003321 SpvId header = this->nextId(nullptr);
3322 SpvId start = this->nextId(nullptr);
3323 SpvId next = this->nextId(nullptr);
3324 SpvId continueTarget = this->nextId(nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003325 fContinueTarget.push(continueTarget);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003326 SpvId end = this->nextId(nullptr);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003327 fBreakTarget.push(end);
3328 this->writeInstruction(SpvOpBranch, header, out);
3329 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003330 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003331 this->writeInstruction(SpvOpBranch, start, out);
3332 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003333 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003334 if (fCurrentBlock) {
3335 this->writeInstruction(SpvOpBranch, next, out);
3336 }
3337 this->writeLabel(next, out);
John Stiles68072a42021-04-16 17:25:55 -04003338 this->writeInstruction(SpvOpBranch, continueTarget, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003339 this->writeLabel(continueTarget, out);
John Stiles68072a42021-04-16 17:25:55 -04003340 SpvId test = this->writeExpression(*d.test(), out);
3341 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003342 this->writeLabel(end, out);
3343 fBreakTarget.pop();
3344 fContinueTarget.pop();
3345}
3346
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003347void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003348 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003349 std::vector<SpvId> labels;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003350 SpvId end = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003351 SpvId defaultLabel = end;
3352 fBreakTarget.push(end);
3353 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003354 auto& cases = s.cases();
John Stilesb23a64b2021-03-11 08:27:59 -05003355 for (const std::unique_ptr<Statement>& stmt : cases) {
3356 const SwitchCase& c = stmt->as<SwitchCase>();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003357 SpvId label = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003358 labels.push_back(label);
John Stilesb23a64b2021-03-11 08:27:59 -05003359 if (c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003360 size += 2;
3361 } else {
3362 defaultLabel = label;
3363 }
3364 }
3365 labels.push_back(end);
3366 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3367 this->writeOpCode(SpvOpSwitch, size, out);
3368 this->writeWord(value, out);
3369 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003370 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003371 const SwitchCase& c = cases[i]->as<SwitchCase>();
3372 if (!c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003373 continue;
3374 }
John Stilesb23a64b2021-03-11 08:27:59 -05003375 this->writeWord(c.value()->as<IntLiteral>().value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003376 this->writeWord(labels[i], out);
3377 }
John Stiles2d4f9592020-10-30 10:29:12 -04003378 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003379 const SwitchCase& c = cases[i]->as<SwitchCase>();
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003380 this->writeLabel(labels[i], out);
John Stilesb23a64b2021-03-11 08:27:59 -05003381 this->writeStatement(*c.statement(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003382 if (fCurrentBlock) {
3383 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3384 }
3385 }
3386 this->writeLabel(end, out);
3387 fBreakTarget.pop();
3388}
3389
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003390void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003391 if (r.expression()) {
3392 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003393 out);
3394 } else {
3395 this->writeInstruction(SpvOpReturn, out);
3396 }
3397}
3398
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003399void SPIRVCodeGenerator::writeGeometryShaderExecutionMode(SpvId entryPoint, OutputStream& out) {
John Stiles270cec22021-02-17 12:59:36 -05003400 SkASSERT(fProgram.fConfig->fKind == ProgramKind::kGeometry);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003401 int invocations = 1;
Brian Osman133724c2020-10-28 14:14:39 -04003402 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003403 if (e->is<ModifiersDeclaration>()) {
Ethan Nicholas077050b2020-10-13 10:30:20 -04003404 const Modifiers& m = e->as<ModifiersDeclaration>().modifiers();
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003405 if (m.fFlags & Modifiers::kIn_Flag) {
3406 if (m.fLayout.fInvocations != -1) {
3407 invocations = m.fLayout.fInvocations;
3408 }
3409 SpvId input;
3410 switch (m.fLayout.fPrimitive) {
3411 case Layout::kPoints_Primitive:
3412 input = SpvExecutionModeInputPoints;
3413 break;
3414 case Layout::kLines_Primitive:
3415 input = SpvExecutionModeInputLines;
3416 break;
3417 case Layout::kLinesAdjacency_Primitive:
3418 input = SpvExecutionModeInputLinesAdjacency;
3419 break;
3420 case Layout::kTriangles_Primitive:
3421 input = SpvExecutionModeTriangles;
3422 break;
3423 case Layout::kTrianglesAdjacency_Primitive:
3424 input = SpvExecutionModeInputTrianglesAdjacency;
3425 break;
3426 default:
3427 input = 0;
3428 break;
3429 }
Ethan Nicholas81d15112018-07-13 12:48:50 -04003430 update_sk_in_count(m, &fSkInCount);
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003431 if (input) {
3432 this->writeInstruction(SpvOpExecutionMode, entryPoint, input, out);
3433 }
3434 } else if (m.fFlags & Modifiers::kOut_Flag) {
3435 SpvId output;
3436 switch (m.fLayout.fPrimitive) {
3437 case Layout::kPoints_Primitive:
3438 output = SpvExecutionModeOutputPoints;
3439 break;
3440 case Layout::kLineStrip_Primitive:
3441 output = SpvExecutionModeOutputLineStrip;
3442 break;
3443 case Layout::kTriangleStrip_Primitive:
3444 output = SpvExecutionModeOutputTriangleStrip;
3445 break;
3446 default:
3447 output = 0;
3448 break;
3449 }
3450 if (output) {
3451 this->writeInstruction(SpvOpExecutionMode, entryPoint, output, out);
3452 }
3453 if (m.fLayout.fMaxVertices != -1) {
3454 this->writeInstruction(SpvOpExecutionMode, entryPoint,
3455 SpvExecutionModeOutputVertices, m.fLayout.fMaxVertices,
3456 out);
3457 }
3458 }
3459 }
3460 }
3461 this->writeInstruction(SpvOpExecutionMode, entryPoint, SpvExecutionModeInvocations,
3462 invocations, out);
3463}
3464
John Stilese40d1662021-01-29 10:08:50 -05003465// Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
3466static std::shared_ptr<SymbolTable> get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
3467 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
3468}
3469
John Stiles4d6310a2021-01-26 19:58:22 -05003470SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
3471 const FunctionDeclaration& main) {
3472 // Our goal is to synthesize a tiny helper function which looks like this:
3473 // void _entrypoint() { sk_FragColor = main(); }
3474
3475 // Fish a symbol table out of main().
John Stilese40d1662021-01-29 10:08:50 -05003476 std::shared_ptr<SymbolTable> symbolTable = get_top_level_symbol_table(main);
John Stiles4d6310a2021-01-26 19:58:22 -05003477
3478 // Get `sk_FragColor` as a writable reference.
3479 const Symbol* skFragColorSymbol = (*symbolTable)["sk_FragColor"];
3480 SkASSERT(skFragColorSymbol);
3481 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
3482 auto skFragColorRef = std::make_unique<VariableReference>(/*offset=*/-1, &skFragColorVar,
3483 VariableReference::RefKind::kWrite);
3484 // Synthesize a call to the `main()` function.
3485 if (main.returnType() != skFragColorRef->type()) {
3486 fErrors.error(main.fOffset, "SPIR-V does not support returning '" +
3487 main.returnType().description() + "' from main()");
3488 return {};
3489 }
Brian Osman716aeb92021-04-21 13:20:00 -04003490 ExpressionArray args;
3491 if (main.parameters().size() == 1) {
3492 if (main.parameters()[0]->type() != *fContext.fTypes.fFloat2) {
3493 fErrors.error(main.fOffset,
3494 "SPIR-V does not support parameter of type '" +
3495 main.parameters()[0]->type().description() + "' to main()");
3496 return {};
3497 }
3498 auto zero = std::make_unique<FloatLiteral>(
3499 /*offset=*/-1, 0.0f, fContext.fTypes.fFloatLiteral.get());
3500 auto zeros = std::make_unique<ConstructorSplat>(
3501 /*offset=*/-1, *fContext.fTypes.fFloat2, std::move(zero));
3502 args.push_back(std::move(zeros));
3503 }
John Stiles4d6310a2021-01-26 19:58:22 -05003504 auto callMainFn = std::make_unique<FunctionCall>(/*offset=*/-1, &main.returnType(), &main,
Brian Osman716aeb92021-04-21 13:20:00 -04003505 std::move(args));
John Stiles4d6310a2021-01-26 19:58:22 -05003506
3507 // Synthesize `skFragColor = main()` as a BinaryExpression.
3508 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
3509 /*offset=*/-1,
3510 std::move(skFragColorRef),
3511 Token::Kind::TK_EQ,
3512 std::move(callMainFn),
3513 &main.returnType()));
3514
3515 // Function bodies are always wrapped in a Block.
3516 StatementArray entrypointStmts;
3517 entrypointStmts.push_back(std::move(assignmentStmt));
John Stilesbf16b6c2021-03-12 19:24:31 -05003518 auto entrypointBlock = Block::Make(/*offset=*/-1, std::move(entrypointStmts),
3519 symbolTable, /*isScope=*/true);
John Stiles4d6310a2021-01-26 19:58:22 -05003520 // Declare an entrypoint function.
3521 EntrypointAdapter adapter;
3522 adapter.fLayout = {};
3523 adapter.fModifiers = Modifiers{adapter.fLayout, Modifiers::kHasSideEffects_Flag};
3524 adapter.entrypointDecl =
3525 std::make_unique<FunctionDeclaration>(/*offset=*/-1,
3526 &adapter.fModifiers,
3527 "_entrypoint",
3528 /*parameters=*/std::vector<const Variable*>{},
3529 /*returnType=*/fContext.fTypes.fVoid.get(),
3530 /*builtin=*/false);
3531 // Define it.
3532 adapter.entrypointDef =
3533 std::make_unique<FunctionDefinition>(/*offset=*/-1, adapter.entrypointDecl.get(),
3534 /*builtin=*/false,
3535 /*body=*/std::move(entrypointBlock));
3536
3537 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
3538 return adapter;
3539}
3540
John Stilese40d1662021-01-29 10:08:50 -05003541void SPIRVCodeGenerator::writeUniformBuffer(std::shared_ptr<SymbolTable> topLevelSymbolTable) {
3542 SkASSERT(!fTopLevelUniforms.empty());
3543 static constexpr char kUniformBufferName[] = "_UniformBuffer";
3544
3545 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
3546 // a lookup table of variables to UniformBuffer field indices.
3547 std::vector<Type::Field> fields;
3548 fields.reserve(fTopLevelUniforms.size());
3549 fTopLevelUniformMap.reserve(fTopLevelUniforms.size());
3550 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
3551 const Variable* var = &topLevelUniform->var();
3552 fTopLevelUniformMap[var] = (int)fields.size();
3553 fields.emplace_back(var->modifiers(), var->name(), &var->type());
3554 }
3555 fUniformBuffer.fStruct = Type::MakeStructType(/*offset=*/-1, kUniformBufferName,
3556 std::move(fields));
3557
3558 // Create a global variable to contain this struct.
3559 Layout layout;
John Stiles270cec22021-02-17 12:59:36 -05003560 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
3561 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilese40d1662021-01-29 10:08:50 -05003562 Modifiers modifiers{layout, Modifiers::kUniform_Flag};
3563
3564 fUniformBuffer.fInnerVariable = std::make_unique<Variable>(
John Stilesf2872e62021-05-04 11:38:43 -04003565 /*offset=*/-1, fProgram.fModifiers->add(modifiers), kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003566 fUniformBuffer.fStruct.get(), /*builtin=*/false, Variable::Storage::kGlobal);
3567
3568 // Create an interface block object for this global variable.
3569 fUniformBuffer.fInterfaceBlock = std::make_unique<InterfaceBlock>(
3570 /*offset=*/-1, fUniformBuffer.fInnerVariable.get(), kUniformBufferName,
3571 kUniformBufferName, /*arraySize=*/0, topLevelSymbolTable);
3572
3573 // Generate an interface block and hold onto its ID.
3574 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
3575}
3576
Brian Salomond8d85b92021-07-07 09:41:17 -04003577void SPIRVCodeGenerator::addRTFlipUniform(int offset) {
3578 if (fWroteRTFlip) {
3579 return;
3580 }
3581 // Flip variable hasn't been written yet. This means we don't have an existing
3582 // interface block, so we're free to just synthesize one.
3583 fWroteRTFlip = true;
3584 std::vector<Type::Field> fields;
3585 if (fProgram.fConfig->fSettings.fRTFlipOffset < 0) {
3586 fErrors.error(offset, "RTFlipOffset is negative");
3587 }
3588 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3589 /*location=*/-1,
3590 fProgram.fConfig->fSettings.fRTFlipOffset,
3591 /*binding=*/-1,
3592 /*index=*/-1,
3593 /*set=*/-1,
3594 /*builtin=*/-1,
3595 /*inputAttachmentIndex=*/-1,
3596 Layout::kUnspecified_Primitive,
3597 /*maxVertices=*/1,
Brian Osman8c264792021-07-01 16:41:27 -04003598 /*invocations=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003599 /*flags=*/0),
3600 SKSL_RTFLIP_NAME,
3601 fContext.fTypes.fFloat2.get());
Ethan Nicholas27f06eb2021-07-26 16:39:40 -04003602 skstd::string_view name = "sksl_synthetic_uniforms";
Brian Salomond8d85b92021-07-07 09:41:17 -04003603 const Type* intfStruct =
3604 fSynthetics.takeOwnershipOfSymbol(Type::MakeStructType(/*offset=*/-1, name, fields));
3605 int binding = fProgram.fConfig->fSettings.fRTFlipBinding;
3606 if (binding == -1) {
3607 fErrors.error(offset, "layout(binding=...) is required in SPIR-V");
3608 }
3609 int set = fProgram.fConfig->fSettings.fRTFlipSet;
3610 if (set == -1) {
3611 fErrors.error(offset, "layout(set=...) is required in SPIR-V");
3612 }
3613 bool usePushConstants = fProgram.fConfig->fSettings.fUsePushConstants;
3614 int flags = usePushConstants ? Layout::Flag::kPushConstant_Flag : 0;
3615 if (fProgram.fPool) {
3616 fProgram.fPool->attachToThread();
3617 }
3618 Modifiers modifiers(Layout(flags,
3619 /*location=*/-1,
3620 /*offset=*/-1,
3621 binding,
3622 /*index=*/-1,
3623 set,
3624 /*builtin=*/-1,
3625 /*inputAttachmentIndex=*/-1,
3626 Layout::kUnspecified_Primitive,
3627 /*maxVertices=*/-1,
Brian Osman8c264792021-07-01 16:41:27 -04003628 /*invocations=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003629 Modifiers::kUniform_Flag);
3630 const Modifiers* modsPtr = fProgram.fModifiers->add(modifiers);
3631 if (fProgram.fPool) {
3632 fProgram.fPool->detachFromThread();
3633 }
3634 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
3635 std::make_unique<Variable>(/*offset=*/-1,
3636 modsPtr,
3637 name,
3638 intfStruct,
3639 /*builtin=*/false,
3640 Variable::Storage::kGlobal));
John Stilesd7437ee2021-08-02 11:56:16 -04003641 fSPIRVBonusVariables.insert(intfVar);
Brian Salomond8d85b92021-07-07 09:41:17 -04003642 if (fProgram.fPool) {
3643 fProgram.fPool->attachToThread();
3644 }
3645 fProgram.fSymbols->add(std::make_unique<Field>(/*offset=*/-1, intfVar, /*field=*/0));
3646 if (fProgram.fPool) {
3647 fProgram.fPool->detachFromThread();
3648 }
3649 InterfaceBlock intf(/*offset=*/-1,
3650 intfVar,
Ethan Nicholas27f06eb2021-07-26 16:39:40 -04003651 String(name),
Brian Salomond8d85b92021-07-07 09:41:17 -04003652 /*instanceName=*/"",
3653 /*arraySize=*/0,
3654 std::make_shared<SymbolTable>(&fErrors, /*builtin=*/false));
3655
3656 this->writeInterfaceBlock(intf, false);
3657}
3658
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003659void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003660 fGLSLExtendedInstructions = this->nextId(nullptr);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003661 StringStream body;
John Stiles4d6310a2021-01-26 19:58:22 -05003662 // Assign SpvIds to functions.
3663 const FunctionDeclaration* main = nullptr;
Brian Osman133724c2020-10-28 14:14:39 -04003664 for (const ProgramElement* e : program.elements()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003665 if (e->is<FunctionDefinition>()) {
3666 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
3667 const FunctionDeclaration& funcDecl = funcDef.declaration();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003668 fFunctionMap[&funcDecl] = this->nextId(nullptr);
John Stilese8da4d22021-03-24 09:19:45 -04003669 if (funcDecl.isMain()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003670 main = &funcDecl;
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003671 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003672 }
3673 }
John Stiles4d6310a2021-01-26 19:58:22 -05003674 // Make sure we have a main() function.
3675 if (!main) {
3676 fErrors.error(/*offset=*/0, "program does not contain a main() function");
3677 return;
3678 }
3679 // Emit interface blocks.
3680 std::set<SpvId> interfaceVars;
Brian Osman133724c2020-10-28 14:14:39 -04003681 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003682 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003683 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003684 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003685
3686 const Modifiers& modifiers = intf.variable().modifiers();
John Stiles8e2a84b2021-04-19 09:35:38 -04003687 if ((modifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003688 modifiers.fLayout.fBuiltin == -1 && !this->isDead(intf.variable())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003689 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003690 }
3691 }
3692 }
John Stiles4d6310a2021-01-26 19:58:22 -05003693 // Emit global variable declarations.
Brian Osman133724c2020-10-28 14:14:39 -04003694 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003695 if (e->is<GlobalVarDeclaration>()) {
John Stiles270cec22021-02-17 12:59:36 -05003696 this->writeGlobalVar(program.fConfig->fKind,
John Stilese40d1662021-01-29 10:08:50 -05003697 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07003698 }
3699 }
John Stilese40d1662021-01-29 10:08:50 -05003700 // Emit top-level uniforms into a dedicated uniform buffer.
3701 if (!fTopLevelUniforms.empty()) {
3702 this->writeUniformBuffer(get_top_level_symbol_table(*main));
3703 }
John Stiles4d6310a2021-01-26 19:58:22 -05003704 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
3705 // main() and stores the result into sk_FragColor.
3706 EntrypointAdapter adapter;
3707 if (main->returnType() == *fContext.fTypes.fHalf4) {
3708 adapter = this->writeEntrypointAdapter(*main);
3709 if (adapter.entrypointDecl) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003710 fFunctionMap[adapter.entrypointDecl.get()] = this->nextId(nullptr);
John Stiles4d6310a2021-01-26 19:58:22 -05003711 this->writeFunction(*adapter.entrypointDef, body);
3712 main = adapter.entrypointDecl.get();
3713 }
3714 }
3715 // Emit all the functions.
Brian Osman133724c2020-10-28 14:14:39 -04003716 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003717 if (e->is<FunctionDefinition>()) {
3718 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003719 }
3720 }
John Stiles4d6310a2021-01-26 19:58:22 -05003721 // Add global in/out variables to the list of interface variables.
ethannicholasb3058bd2016-07-01 08:22:01 -07003722 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003723 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003724 if (var->storage() == Variable::Storage::kGlobal &&
John Stiles8e2a84b2021-04-19 09:35:38 -04003725 (var->modifiers().fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003726 !this->isDead(*var)) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003727 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003728 }
3729 }
3730 this->writeCapabilities(out);
3731 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3732 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003733 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().length() + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003734 (int32_t) interfaceVars.size(), out);
John Stiles270cec22021-02-17 12:59:36 -05003735 switch (program.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05003736 case ProgramKind::kVertex:
ethannicholasb3058bd2016-07-01 08:22:01 -07003737 this->writeWord(SpvExecutionModelVertex, out);
3738 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003739 case ProgramKind::kFragment:
ethannicholasb3058bd2016-07-01 08:22:01 -07003740 this->writeWord(SpvExecutionModelFragment, out);
3741 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003742 case ProgramKind::kGeometry:
Ethan Nicholas52cad152017-02-16 16:37:32 -05003743 this->writeWord(SpvExecutionModelGeometry, out);
3744 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003745 default:
John Stilesf57207b2021-02-02 17:50:34 -05003746 SK_ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003747 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003748 SpvId entryPoint = fFunctionMap[main];
3749 this->writeWord(entryPoint, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003750 this->writeString(main->name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003751 for (int var : interfaceVars) {
3752 this->writeWord(var, out);
3753 }
John Stiles270cec22021-02-17 12:59:36 -05003754 if (program.fConfig->fKind == ProgramKind::kGeometry) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003755 this->writeGeometryShaderExecutionMode(entryPoint, out);
3756 }
John Stiles270cec22021-02-17 12:59:36 -05003757 if (program.fConfig->fKind == ProgramKind::kFragment) {
Greg Daniel64773e62016-11-22 09:44:03 -05003758 this->writeInstruction(SpvOpExecutionMode,
3759 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003760 SpvExecutionModeOriginUpperLeft,
3761 out);
3762 }
Brian Osman133724c2020-10-28 14:14:39 -04003763 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003764 if (e->is<Extension>()) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003765 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003766 }
3767 }
Greg Daniel64773e62016-11-22 09:44:03 -05003768
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003769 write_stringstream(fExtraGlobalsBuffer, out);
3770 write_stringstream(fNameBuffer, out);
3771 write_stringstream(fDecorationBuffer, out);
3772 write_stringstream(fConstantBuffer, out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003773 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003774}
3775
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003776bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04003777 SkASSERT(!fErrors.errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003778 this->writeWord(SpvMagicNumber, *fOut);
3779 this->writeWord(SpvVersion, *fOut);
3780 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003781 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003782 this->writeInstructions(fProgram, buffer);
3783 this->writeWord(fIdCount, *fOut);
3784 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003785 write_stringstream(buffer, *fOut);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003786 return 0 == fErrors.errorCount();
ethannicholasb3058bd2016-07-01 08:22:01 -07003787}
3788
John Stilesa6841be2020-08-06 14:11:56 -04003789} // namespace SkSL