blob: 47e80a0b1fbb7c804ab60096ac26382a4c72883f [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"
John Stilese3ae9682021-08-05 10:35:01 -040017#include "src/sksl/ir/SkSLConstructorArrayCast.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050018#include "src/sksl/ir/SkSLExpressionStatement.h"
19#include "src/sksl/ir/SkSLExtension.h"
Brian Salomond8d85b92021-07-07 09:41:17 -040020#include "src/sksl/ir/SkSLField.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050021#include "src/sksl/ir/SkSLIndexExpression.h"
22#include "src/sksl/ir/SkSLVariableReference.h"
ethannicholasb3058bd2016-07-01 08:22:01 -070023
Ethan Nicholas0be34802019-08-15 12:36:58 -040024#ifdef SK_VULKAN
25#include "src/gpu/vk/GrVkCaps.h"
26#endif
27
John Stilescd806892021-01-06 13:33:31 -050028#define kLast_Capability SpvCapabilityMultiViewport
29
Brian Salomond8d85b92021-07-07 09:41:17 -040030constexpr int DEVICE_FRAGCOORDS_BUILTIN = -1000;
31constexpr int DEVICE_CLOCKWISE_BUILTIN = -1001;
32
ethannicholasb3058bd2016-07-01 08:22:01 -070033namespace SkSL {
34
ethannicholasb3058bd2016-07-01 08:22:01 -070035static const int32_t SKSL_MAGIC = 0x0; // FIXME: we should probably register a magic number
36
37void SPIRVCodeGenerator::setupIntrinsics() {
John Stilesaaac4e42021-05-06 14:08:28 -040038#define ALL_GLSL(x) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, GLSLstd450 ## x, \
39 GLSLstd450 ## x, GLSLstd450 ## x, GLSLstd450 ## x)
40#define BY_TYPE_GLSL(ifFloat, ifInt, ifUInt) std::make_tuple(kGLSL_STD_450_IntrinsicOpcodeKind, \
41 GLSLstd450 ## ifFloat, \
42 GLSLstd450 ## ifInt, \
43 GLSLstd450 ## ifUInt, \
ethannicholasb3058bd2016-07-01 08:22:01 -070044 SpvOpUndef)
John Stilesaaac4e42021-05-06 14:08:28 -040045#define ALL_SPIRV(x) std::make_tuple(kSPIRV_IntrinsicOpcodeKind, \
46 SpvOp ## x, SpvOp ## x, SpvOp ## x, SpvOp ## x)
47#define SPECIAL(x) std::make_tuple(kSpecial_IntrinsicOpcodeKind, k ## x ## _SpecialIntrinsic, \
48 k ## x ## _SpecialIntrinsic, k ## x ## _SpecialIntrinsic, \
ethannicholasb3058bd2016-07-01 08:22:01 -070049 k ## x ## _SpecialIntrinsic)
John Stilesaaac4e42021-05-06 14:08:28 -040050 fIntrinsicMap[k_round_IntrinsicKind] = ALL_GLSL(Round);
51 fIntrinsicMap[k_roundEven_IntrinsicKind] = ALL_GLSL(RoundEven);
52 fIntrinsicMap[k_trunc_IntrinsicKind] = ALL_GLSL(Trunc);
53 fIntrinsicMap[k_abs_IntrinsicKind] = BY_TYPE_GLSL(FAbs, SAbs, SAbs);
54 fIntrinsicMap[k_sign_IntrinsicKind] = BY_TYPE_GLSL(FSign, SSign, SSign);
55 fIntrinsicMap[k_floor_IntrinsicKind] = ALL_GLSL(Floor);
56 fIntrinsicMap[k_ceil_IntrinsicKind] = ALL_GLSL(Ceil);
57 fIntrinsicMap[k_fract_IntrinsicKind] = ALL_GLSL(Fract);
58 fIntrinsicMap[k_radians_IntrinsicKind] = ALL_GLSL(Radians);
59 fIntrinsicMap[k_degrees_IntrinsicKind] = ALL_GLSL(Degrees);
60 fIntrinsicMap[k_sin_IntrinsicKind] = ALL_GLSL(Sin);
61 fIntrinsicMap[k_cos_IntrinsicKind] = ALL_GLSL(Cos);
62 fIntrinsicMap[k_tan_IntrinsicKind] = ALL_GLSL(Tan);
63 fIntrinsicMap[k_asin_IntrinsicKind] = ALL_GLSL(Asin);
64 fIntrinsicMap[k_acos_IntrinsicKind] = ALL_GLSL(Acos);
65 fIntrinsicMap[k_atan_IntrinsicKind] = SPECIAL(Atan);
66 fIntrinsicMap[k_sinh_IntrinsicKind] = ALL_GLSL(Sinh);
67 fIntrinsicMap[k_cosh_IntrinsicKind] = ALL_GLSL(Cosh);
68 fIntrinsicMap[k_tanh_IntrinsicKind] = ALL_GLSL(Tanh);
69 fIntrinsicMap[k_asinh_IntrinsicKind] = ALL_GLSL(Asinh);
70 fIntrinsicMap[k_acosh_IntrinsicKind] = ALL_GLSL(Acosh);
71 fIntrinsicMap[k_atanh_IntrinsicKind] = ALL_GLSL(Atanh);
72 fIntrinsicMap[k_pow_IntrinsicKind] = ALL_GLSL(Pow);
73 fIntrinsicMap[k_exp_IntrinsicKind] = ALL_GLSL(Exp);
74 fIntrinsicMap[k_log_IntrinsicKind] = ALL_GLSL(Log);
75 fIntrinsicMap[k_exp2_IntrinsicKind] = ALL_GLSL(Exp2);
76 fIntrinsicMap[k_log2_IntrinsicKind] = ALL_GLSL(Log2);
77 fIntrinsicMap[k_sqrt_IntrinsicKind] = ALL_GLSL(Sqrt);
78 fIntrinsicMap[k_inverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
79 fIntrinsicMap[k_outerProduct_IntrinsicKind] = ALL_SPIRV(OuterProduct);
80 fIntrinsicMap[k_transpose_IntrinsicKind] = ALL_SPIRV(Transpose);
81 fIntrinsicMap[k_isinf_IntrinsicKind] = ALL_SPIRV(IsInf);
82 fIntrinsicMap[k_isnan_IntrinsicKind] = ALL_SPIRV(IsNan);
83 fIntrinsicMap[k_inversesqrt_IntrinsicKind] = ALL_GLSL(InverseSqrt);
84 fIntrinsicMap[k_determinant_IntrinsicKind] = ALL_GLSL(Determinant);
85 fIntrinsicMap[k_matrixCompMult_IntrinsicKind] = SPECIAL(MatrixCompMult);
86 fIntrinsicMap[k_matrixInverse_IntrinsicKind] = ALL_GLSL(MatrixInverse);
87 fIntrinsicMap[k_mod_IntrinsicKind] = SPECIAL(Mod);
88 fIntrinsicMap[k_modf_IntrinsicKind] = ALL_GLSL(Modf);
89 fIntrinsicMap[k_min_IntrinsicKind] = SPECIAL(Min);
90 fIntrinsicMap[k_max_IntrinsicKind] = SPECIAL(Max);
91 fIntrinsicMap[k_clamp_IntrinsicKind] = SPECIAL(Clamp);
92 fIntrinsicMap[k_saturate_IntrinsicKind] = SPECIAL(Saturate);
93 fIntrinsicMap[k_dot_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
94 SpvOpDot, SpvOpUndef, SpvOpUndef, SpvOpUndef);
95 fIntrinsicMap[k_mix_IntrinsicKind] = SPECIAL(Mix);
96 fIntrinsicMap[k_step_IntrinsicKind] = SPECIAL(Step);
97 fIntrinsicMap[k_smoothstep_IntrinsicKind] = SPECIAL(SmoothStep);
98 fIntrinsicMap[k_fma_IntrinsicKind] = ALL_GLSL(Fma);
99 fIntrinsicMap[k_frexp_IntrinsicKind] = ALL_GLSL(Frexp);
100 fIntrinsicMap[k_ldexp_IntrinsicKind] = ALL_GLSL(Ldexp);
ethannicholasb3058bd2016-07-01 08:22:01 -0700101
John Stilesaaac4e42021-05-06 14:08:28 -0400102#define PACK(type) fIntrinsicMap[k_pack##type##_IntrinsicKind] = ALL_GLSL(Pack##type); \
103 fIntrinsicMap[k_unpack##type##_IntrinsicKind] = ALL_GLSL(Unpack##type)
ethannicholasb3058bd2016-07-01 08:22:01 -0700104 PACK(Snorm4x8);
105 PACK(Unorm4x8);
106 PACK(Snorm2x16);
107 PACK(Unorm2x16);
108 PACK(Half2x16);
109 PACK(Double2x32);
John Stilesaaac4e42021-05-06 14:08:28 -0400110#undef PACK
111 fIntrinsicMap[k_length_IntrinsicKind] = ALL_GLSL(Length);
112 fIntrinsicMap[k_distance_IntrinsicKind] = ALL_GLSL(Distance);
113 fIntrinsicMap[k_cross_IntrinsicKind] = ALL_GLSL(Cross);
114 fIntrinsicMap[k_normalize_IntrinsicKind] = ALL_GLSL(Normalize);
115 fIntrinsicMap[k_faceforward_IntrinsicKind] = ALL_GLSL(FaceForward);
116 fIntrinsicMap[k_reflect_IntrinsicKind] = ALL_GLSL(Reflect);
117 fIntrinsicMap[k_refract_IntrinsicKind] = ALL_GLSL(Refract);
118 fIntrinsicMap[k_bitCount_IntrinsicKind] = ALL_SPIRV(BitCount);
119 fIntrinsicMap[k_findLSB_IntrinsicKind] = ALL_GLSL(FindILsb);
120 fIntrinsicMap[k_findMSB_IntrinsicKind] = BY_TYPE_GLSL(FindSMsb, FindSMsb, FindUMsb);
121 fIntrinsicMap[k_dFdx_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
122 SpvOpDPdx, SpvOpUndef,
123 SpvOpUndef, SpvOpUndef);
124 fIntrinsicMap[k_dFdy_IntrinsicKind] = SPECIAL(DFdy);
125 fIntrinsicMap[k_fwidth_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
126 SpvOpFwidth, SpvOpUndef,
127 SpvOpUndef, SpvOpUndef);
128 fIntrinsicMap[k_makeSampler2D_IntrinsicKind] = SPECIAL(SampledImage);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400129
John Stilesaaac4e42021-05-06 14:08:28 -0400130 fIntrinsicMap[k_sample_IntrinsicKind] = SPECIAL(Texture);
131 fIntrinsicMap[k_subpassLoad_IntrinsicKind] = SPECIAL(SubpassLoad);
Greg Daniel64773e62016-11-22 09:44:03 -0500132
John Stilesaaac4e42021-05-06 14:08:28 -0400133 fIntrinsicMap[k_floatBitsToInt_IntrinsicKind] = ALL_SPIRV(Bitcast);
134 fIntrinsicMap[k_floatBitsToUint_IntrinsicKind] = ALL_SPIRV(Bitcast);
135 fIntrinsicMap[k_intBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
136 fIntrinsicMap[k_uintBitsToFloat_IntrinsicKind] = ALL_SPIRV(Bitcast);
John Stilescc9ff002020-12-09 18:39:41 -0500137
John Stilesaaac4e42021-05-06 14:08:28 -0400138 fIntrinsicMap[k_any_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Brian Osman540c13a2020-11-24 16:55:34 -0500139 SpvOpUndef, SpvOpUndef,
John Stilesaaac4e42021-05-06 14:08:28 -0400140 SpvOpUndef, SpvOpAny);
141 fIntrinsicMap[k_all_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
142 SpvOpUndef, SpvOpUndef,
143 SpvOpUndef, SpvOpAll);
144 fIntrinsicMap[k_not_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
145 SpvOpUndef, SpvOpUndef, SpvOpUndef,
Brian Osman540c13a2020-11-24 16:55:34 -0500146 SpvOpLogicalNot);
John Stilesaaac4e42021-05-06 14:08:28 -0400147 fIntrinsicMap[k_equal_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400148 SpvOpFOrdEqual, SpvOpIEqual,
149 SpvOpIEqual, SpvOpLogicalEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400150 fIntrinsicMap[k_notEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400151 SpvOpFOrdNotEqual, SpvOpINotEqual,
152 SpvOpINotEqual,
153 SpvOpLogicalNotEqual);
John Stilesaaac4e42021-05-06 14:08:28 -0400154 fIntrinsicMap[k_lessThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
155 SpvOpFOrdLessThan,
156 SpvOpSLessThan,
157 SpvOpULessThan,
158 SpvOpUndef);
159 fIntrinsicMap[k_lessThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
160 SpvOpFOrdLessThanEqual,
161 SpvOpSLessThanEqual,
162 SpvOpULessThanEqual,
163 SpvOpUndef);
164 fIntrinsicMap[k_greaterThan_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
165 SpvOpFOrdGreaterThan,
166 SpvOpSGreaterThan,
167 SpvOpUGreaterThan,
168 SpvOpUndef);
169 fIntrinsicMap[k_greaterThanEqual_IntrinsicKind] = std::make_tuple(kSPIRV_IntrinsicOpcodeKind,
170 SpvOpFOrdGreaterThanEqual,
171 SpvOpSGreaterThanEqual,
172 SpvOpUGreaterThanEqual,
173 SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700174// interpolateAt* not yet supported...
175}
176
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400177void SPIRVCodeGenerator::writeWord(int32_t word, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700178 out.write((const char*) &word, sizeof(word));
ethannicholasb3058bd2016-07-01 08:22:01 -0700179}
180
ethannicholasd598f792016-07-25 10:08:54 -0700181static bool is_float(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500182 return (type.isScalar() || type.isVector() || type.isMatrix()) &&
183 type.componentType().isFloat();
ethannicholasb3058bd2016-07-01 08:22:01 -0700184}
185
ethannicholasd598f792016-07-25 10:08:54 -0700186static bool is_signed(const Context& context, const Type& type) {
Brian Osmanc9145f32021-07-08 13:40:10 -0400187 return (type.isScalar() || type.isVector()) && type.componentType().isSigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700188}
189
ethannicholasd598f792016-07-25 10:08:54 -0700190static bool is_unsigned(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500191 return (type.isScalar() || type.isVector()) && type.componentType().isUnsigned();
ethannicholasb3058bd2016-07-01 08:22:01 -0700192}
193
ethannicholasd598f792016-07-25 10:08:54 -0700194static bool is_bool(const Context& context, const Type& type) {
John Stiles4c151702021-02-09 18:31:34 -0500195 return (type.isScalar() || type.isVector()) && type.componentType().isBoolean();
ethannicholasb3058bd2016-07-01 08:22:01 -0700196}
197
John Stiles07367122021-09-08 13:12:26 -0400198static bool is_out(const Modifiers& m) {
199 return (m.fFlags & Modifiers::kOut_Flag) != 0;
ethannicholasb3058bd2016-07-01 08:22:01 -0700200}
201
John Stiles07367122021-09-08 13:12:26 -0400202static bool is_in(const Modifiers& m) {
203 switch (m.fFlags & (Modifiers::kOut_Flag | Modifiers::kIn_Flag)) {
John Stiles6a51b202021-09-08 10:45:08 -0400204 case Modifiers::kOut_Flag: // out
205 return false;
206
207 case 0: // implicit in
208 case Modifiers::kIn_Flag: // explicit in
209 case Modifiers::kOut_Flag | Modifiers::kIn_Flag: // inout
210 return true;
211
212 default: SkUNREACHABLE;
213 }
214}
215
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400216void SPIRVCodeGenerator::writeOpCode(SpvOp_ opCode, int length, OutputStream& out) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400217 SkASSERT(opCode != SpvOpLoad || &out != &fConstantBuffer);
218 SkASSERT(opCode != SpvOpUndef);
ethannicholasb3058bd2016-07-01 08:22:01 -0700219 switch (opCode) {
220 case SpvOpReturn: // fall through
221 case SpvOpReturnValue: // fall through
ethannicholas552882f2016-07-07 06:30:48 -0700222 case SpvOpKill: // fall through
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500223 case SpvOpSwitch: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700224 case SpvOpBranch: // fall through
225 case SpvOpBranchConditional:
John Stilesf2b08cc2021-05-17 14:46:05 -0400226 if (fCurrentBlock == 0) {
227 // We just encountered dead code--instructions that don't have an associated block.
228 // Synthesize a label if this happens; this is necessary to satisfy the validator.
229 this->writeLabel(this->nextId(nullptr), out);
230 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700231 fCurrentBlock = 0;
232 break;
233 case SpvOpConstant: // fall through
234 case SpvOpConstantTrue: // fall through
235 case SpvOpConstantFalse: // fall through
236 case SpvOpConstantComposite: // fall through
237 case SpvOpTypeVoid: // fall through
238 case SpvOpTypeInt: // fall through
239 case SpvOpTypeFloat: // fall through
240 case SpvOpTypeBool: // fall through
241 case SpvOpTypeVector: // fall through
242 case SpvOpTypeMatrix: // fall through
243 case SpvOpTypeArray: // fall through
244 case SpvOpTypePointer: // fall through
245 case SpvOpTypeFunction: // fall through
246 case SpvOpTypeRuntimeArray: // fall through
247 case SpvOpTypeStruct: // fall through
248 case SpvOpTypeImage: // fall through
249 case SpvOpTypeSampledImage: // fall through
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400250 case SpvOpTypeSampler: // fall through
ethannicholasb3058bd2016-07-01 08:22:01 -0700251 case SpvOpVariable: // fall through
252 case SpvOpFunction: // fall through
253 case SpvOpFunctionParameter: // fall through
254 case SpvOpFunctionEnd: // fall through
255 case SpvOpExecutionMode: // fall through
256 case SpvOpMemoryModel: // fall through
257 case SpvOpCapability: // fall through
258 case SpvOpExtInstImport: // fall through
259 case SpvOpEntryPoint: // fall through
260 case SpvOpSource: // fall through
261 case SpvOpSourceExtension: // fall through
262 case SpvOpName: // fall through
263 case SpvOpMemberName: // fall through
264 case SpvOpDecorate: // fall through
265 case SpvOpMemberDecorate:
266 break;
267 default:
John Stilesf3a28db2021-03-10 23:00:47 -0500268 // We may find ourselves with dead code--instructions that don't have an associated
269 // block. This should be a rare event, but if it happens, synthesize a label; this is
270 // necessary to satisfy the validator.
271 if (fCurrentBlock == 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400272 this->writeLabel(this->nextId(nullptr), out);
John Stiles7142e402021-02-23 12:28:18 -0500273 }
John Stiles453f1432021-02-25 16:58:04 -0500274 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700275 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700276 this->writeWord((length << 16) | opCode, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700277}
278
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400279void SPIRVCodeGenerator::writeLabel(SpvId label, OutputStream& out) {
Ethan Nicholas7fb39362020-12-16 15:25:19 -0500280 SkASSERT(!fCurrentBlock);
ethannicholasb3058bd2016-07-01 08:22:01 -0700281 fCurrentBlock = label;
282 this->writeInstruction(SpvOpLabel, label, out);
283}
284
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400285void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700286 this->writeOpCode(opCode, 1, out);
287}
288
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400289void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700290 this->writeOpCode(opCode, 2, out);
291 this->writeWord(word1, out);
292}
293
Ethan Nicholas962dec42021-06-10 13:06:39 -0400294void SPIRVCodeGenerator::writeString(skstd::string_view s, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400295 out.write(s.data(), s.length());
296 switch (s.length() % 4) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700297 case 1:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500298 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400299 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700300 case 2:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500301 out.write8(0);
John Stiles30212b72020-06-11 17:55:07 -0400302 [[fallthrough]];
ethannicholasb3058bd2016-07-01 08:22:01 -0700303 case 3:
Ethan Nicholas9e1138d2016-11-21 10:39:35 -0500304 out.write8(0);
ethannicholasb3058bd2016-07-01 08:22:01 -0700305 break;
306 default:
307 this->writeWord(0, out);
Ethan Nicholasb13f3692021-09-10 16:49:42 -0400308 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700309 }
310}
311
Ethan Nicholas962dec42021-06-10 13:06:39 -0400312void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, skstd::string_view string,
313 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400314 this->writeOpCode(opCode, 1 + (string.length() + 4) / 4, out);
315 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700316}
317
318
Ethan Nicholas962dec42021-06-10 13:06:39 -0400319void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, skstd::string_view string,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400320 OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400321 this->writeOpCode(opCode, 2 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700322 this->writeWord(word1, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400323 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700324}
325
Greg Daniel64773e62016-11-22 09:44:03 -0500326void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400327 skstd::string_view string, OutputStream& out) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400328 this->writeOpCode(opCode, 3 + (string.length() + 4) / 4, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700329 this->writeWord(word1, out);
330 this->writeWord(word2, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400331 this->writeString(string, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700332}
333
Greg Daniel64773e62016-11-22 09:44:03 -0500334void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400335 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700336 this->writeOpCode(opCode, 3, out);
337 this->writeWord(word1, out);
338 this->writeWord(word2, out);
339}
340
Greg Daniel64773e62016-11-22 09:44:03 -0500341void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400342 int32_t word3, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700343 this->writeOpCode(opCode, 4, out);
344 this->writeWord(word1, out);
345 this->writeWord(word2, out);
346 this->writeWord(word3, out);
347}
348
Greg Daniel64773e62016-11-22 09:44:03 -0500349void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400350 int32_t word3, int32_t word4, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700351 this->writeOpCode(opCode, 5, out);
352 this->writeWord(word1, out);
353 this->writeWord(word2, out);
354 this->writeWord(word3, out);
355 this->writeWord(word4, out);
356}
357
Greg Daniel64773e62016-11-22 09:44:03 -0500358void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
359 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400360 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700361 this->writeOpCode(opCode, 6, out);
362 this->writeWord(word1, out);
363 this->writeWord(word2, out);
364 this->writeWord(word3, out);
365 this->writeWord(word4, out);
366 this->writeWord(word5, out);
367}
368
Greg Daniel64773e62016-11-22 09:44:03 -0500369void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700370 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400371 int32_t word6, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700372 this->writeOpCode(opCode, 7, out);
373 this->writeWord(word1, out);
374 this->writeWord(word2, out);
375 this->writeWord(word3, out);
376 this->writeWord(word4, out);
377 this->writeWord(word5, out);
378 this->writeWord(word6, out);
379}
380
Greg Daniel64773e62016-11-22 09:44:03 -0500381void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700382 int32_t word3, int32_t word4, int32_t word5,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400383 int32_t word6, int32_t word7, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700384 this->writeOpCode(opCode, 8, 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}
393
Greg Daniel64773e62016-11-22 09:44:03 -0500394void SPIRVCodeGenerator::writeInstruction(SpvOp_ opCode, int32_t word1, int32_t word2,
ethannicholasb3058bd2016-07-01 08:22:01 -0700395 int32_t word3, int32_t word4, int32_t word5,
396 int32_t word6, int32_t word7, int32_t word8,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400397 OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700398 this->writeOpCode(opCode, 9, out);
399 this->writeWord(word1, out);
400 this->writeWord(word2, out);
401 this->writeWord(word3, out);
402 this->writeWord(word4, out);
403 this->writeWord(word5, out);
404 this->writeWord(word6, out);
405 this->writeWord(word7, out);
406 this->writeWord(word8, out);
407}
408
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400409void SPIRVCodeGenerator::writeCapabilities(OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700410 for (uint64_t i = 0, bit = 1; i <= kLast_Capability; i++, bit <<= 1) {
411 if (fCapabilities & bit) {
412 this->writeInstruction(SpvOpCapability, (SpvId) i, out);
413 }
414 }
Brian Osman99ddd2a2021-08-27 11:21:12 -0400415 this->writeInstruction(SpvOpCapability, SpvCapabilityShader, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700416}
417
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400418SpvId SPIRVCodeGenerator::nextId(const Type* type) {
419 return this->nextId(type && type->hasPrecision() && !type->highPrecision()
420 ? Precision::kRelaxed
421 : Precision::kDefault);
422}
423
424SpvId SPIRVCodeGenerator::nextId(Precision precision) {
425 if (precision == Precision::kRelaxed && !fProgram.fConfig->fSettings.fForceHighPrecision) {
426 this->writeInstruction(SpvOpDecorate, fIdCount, SpvDecorationRelaxedPrecision,
427 fDecorationBuffer);
428 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700429 return fIdCount++;
430}
431
Ethan Nicholas19671772016-11-28 16:30:17 -0500432void SPIRVCodeGenerator::writeStruct(const Type& type, const MemoryLayout& memoryLayout,
433 SpvId resultId) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400434 this->writeInstruction(SpvOpName, resultId, String(type.name()).c_str(), fNameBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700435 // go ahead and write all of the field types, so we don't inadvertently write them while we're
436 // in the middle of writing the struct instruction
437 std::vector<SpvId> types;
438 for (const auto& f : type.fields()) {
Ethan Nicholas19671772016-11-28 16:30:17 -0500439 types.push_back(this->getType(*f.fType, memoryLayout));
ethannicholasb3058bd2016-07-01 08:22:01 -0700440 }
441 this->writeOpCode(SpvOpTypeStruct, 2 + (int32_t) types.size(), fConstantBuffer);
442 this->writeWord(resultId, fConstantBuffer);
443 for (SpvId id : types) {
444 this->writeWord(id, fConstantBuffer);
445 }
446 size_t offset = 0;
447 for (int32_t i = 0; i < (int32_t) type.fields().size(); i++) {
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400448 const Type::Field& field = type.fields()[i];
John Stiles21f5f452020-11-30 09:57:59 -0500449 if (!MemoryLayout::LayoutIsSupported(*field.fType)) {
Brian Osmancc914522021-09-24 18:58:37 +0000450 fContext.fErrors->error(type.fOffset, "type '" + field.fType->name() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400451 "' is not permitted here");
John Stiles0023c0c2020-11-16 13:32:18 -0500452 return;
453 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400454 size_t size = memoryLayout.size(*field.fType);
455 size_t alignment = memoryLayout.alignment(*field.fType);
456 const Layout& fieldLayout = field.fModifiers.fLayout;
Ethan Nicholas19671772016-11-28 16:30:17 -0500457 if (fieldLayout.fOffset >= 0) {
Greg Danieldbd44c72017-01-24 15:12:12 -0500458 if (fieldLayout.fOffset < (int) offset) {
Brian Osmancc914522021-09-24 18:58:37 +0000459 fContext.fErrors->error(type.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400460 "offset of field '" + field.fName + "' must be at "
461 "least " + to_string((int) offset));
Ethan Nicholas19671772016-11-28 16:30:17 -0500462 }
463 if (fieldLayout.fOffset % alignment) {
Brian Osmancc914522021-09-24 18:58:37 +0000464 fContext.fErrors->error(type.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400465 "offset of field '" + field.fName + "' must be a multiple"
466 " of " + to_string((int) alignment));
Ethan Nicholas19671772016-11-28 16:30:17 -0500467 }
468 offset = fieldLayout.fOffset;
469 } else {
470 size_t mod = offset % alignment;
471 if (mod) {
472 offset += alignment - mod;
473 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700474 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400475 this->writeInstruction(SpvOpMemberName, resultId, i, field.fName, fNameBuffer);
Ethan Nicholas19671772016-11-28 16:30:17 -0500476 this->writeLayout(fieldLayout, resultId, i);
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400477 if (field.fModifiers.fLayout.fBuiltin < 0) {
Greg Daniel64773e62016-11-22 09:44:03 -0500478 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i, SpvDecorationOffset,
ethannicholasb3058bd2016-07-01 08:22:01 -0700479 (SpvId) offset, fDecorationBuffer);
480 }
John Stiles9aeed132020-11-24 17:36:06 -0500481 if (field.fType->isMatrix()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500482 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationColMajor,
ethannicholasb3058bd2016-07-01 08:22:01 -0700483 fDecorationBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500484 this->writeInstruction(SpvOpMemberDecorate, resultId, i, SpvDecorationMatrixStride,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400485 (SpvId) memoryLayout.stride(*field.fType),
ethannicholas8ac838d2016-11-22 08:39:36 -0800486 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700487 }
Ethan Nicholascc5d3e02019-04-19 09:50:56 -0400488 if (!field.fType->highPrecision()) {
489 this->writeInstruction(SpvOpMemberDecorate, resultId, (SpvId) i,
490 SpvDecorationRelaxedPrecision, fDecorationBuffer);
491 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700492 offset += size;
John Stilesc0c51062020-12-03 17:16:29 -0500493 if ((field.fType->isArray() || field.fType->isStruct()) && offset % alignment != 0) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700494 offset += alignment - offset % alignment;
495 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700496 }
497}
498
Ethan Nicholase2c49992020-10-05 11:49:11 -0400499const Type& SPIRVCodeGenerator::getActualType(const Type& type) {
Ethan Nicholase1f55022019-02-05 17:17:40 -0500500 if (type.isFloat()) {
John Stiles54e7c052021-01-11 14:22:36 -0500501 return *fContext.fTypes.fFloat;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400502 }
Brian Osmanc9145f32021-07-08 13:40:10 -0400503 if (type.isSigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500504 return *fContext.fTypes.fInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400505 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500506 if (type.isUnsigned()) {
John Stiles54e7c052021-01-11 14:22:36 -0500507 return *fContext.fTypes.fUInt;
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400508 }
John Stiles9aeed132020-11-24 17:36:06 -0500509 if (type.isMatrix() || type.isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -0500510 if (type.componentType() == *fContext.fTypes.fHalf) {
511 return fContext.fTypes.fFloat->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400512 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400513 if (type.componentType() == *fContext.fTypes.fShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500514 return fContext.fTypes.fInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400515 }
Ethan Nicholas722c83e2021-05-04 11:39:30 -0400516 if (type.componentType() == *fContext.fTypes.fUShort) {
John Stiles54e7c052021-01-11 14:22:36 -0500517 return fContext.fTypes.fUInt->toCompound(fContext, type.columns(), type.rows());
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400518 }
519 }
520 return type;
521}
522
ethannicholasb3058bd2016-07-01 08:22:01 -0700523SpvId SPIRVCodeGenerator::getType(const Type& type) {
ethannicholas8ac838d2016-11-22 08:39:36 -0800524 return this->getType(type, fDefaultLayout);
525}
526
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400527SpvId SPIRVCodeGenerator::getType(const Type& rawType, const MemoryLayout& layout) {
John Stiles3c991fd2021-08-09 14:19:58 -0400528 const Type* type;
529 std::unique_ptr<Type> arrayType;
530 String arrayName;
531
532 if (rawType.isArray()) {
533 // For arrays, we need to synthesize a temporary Array type using the "actual" component
534 // type. That is, if `short[10]` is passed in, we need to synthesize a `int[10]` Type.
535 // Otherwise, we can end up with two different SpvIds for the same array type.
536 const Type& component = this->getActualType(rawType.componentType());
537 arrayName = component.getArrayName(rawType.columns());
538 arrayType = Type::MakeArrayType(arrayName, component, rawType.columns());
539 type = arrayType.get();
540 } else {
541 // For non-array types, we can simply look up the "actual" type and use it.
542 type = &this->getActualType(rawType);
543 }
544
545 String key(type->name());
546 if (type->isStruct() || type->isArray()) {
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400547 key += to_string((int)layout.fStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500548#ifdef SK_DEBUG
549 SkASSERT(layout.fStd == MemoryLayout::Standard::k140_Standard ||
550 layout.fStd == MemoryLayout::Standard::k430_Standard);
551 MemoryLayout::Standard otherStd = layout.fStd == MemoryLayout::Standard::k140_Standard
552 ? MemoryLayout::Standard::k430_Standard
553 : MemoryLayout::Standard::k140_Standard;
John Stiles3c991fd2021-08-09 14:19:58 -0400554 String otherKey = type->name() + to_string((int)otherStd);
Brian Osman2a4c0fb2021-01-22 13:41:40 -0500555 SkASSERT(fTypeMap.find(otherKey) == fTypeMap.end());
556#endif
Jim Van Verthf3ec9832020-10-21 16:09:57 -0400557 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800558 auto entry = fTypeMap.find(key);
ethannicholasb3058bd2016-07-01 08:22:01 -0700559 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400560 SpvId result = this->nextId(nullptr);
John Stiles3c991fd2021-08-09 14:19:58 -0400561 switch (type->typeKind()) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400562 case Type::TypeKind::kScalar:
John Stiles3c991fd2021-08-09 14:19:58 -0400563 if (type->isBoolean()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700564 this->writeInstruction(SpvOpTypeBool, result, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400565 } else if (type->isSigned()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700566 this->writeInstruction(SpvOpTypeInt, result, 32, 1, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400567 } else if (type->isUnsigned()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700568 this->writeInstruction(SpvOpTypeInt, result, 32, 0, fConstantBuffer);
John Stiles3c991fd2021-08-09 14:19:58 -0400569 } else if (type->isFloat()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700570 this->writeInstruction(SpvOpTypeFloat, result, 32, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700571 } else {
John Stiles3c991fd2021-08-09 14:19:58 -0400572 SkDEBUGFAILF("unrecognized scalar type '%s'", type->description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700573 }
574 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400575 case Type::TypeKind::kVector:
Greg Daniel64773e62016-11-22 09:44:03 -0500576 this->writeInstruction(SpvOpTypeVector, result,
John Stiles3c991fd2021-08-09 14:19:58 -0400577 this->getType(type->componentType(), layout),
578 type->columns(), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700579 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400580 case Type::TypeKind::kMatrix:
John Stiles51d33982021-03-08 09:18:07 -0500581 this->writeInstruction(
582 SpvOpTypeMatrix,
583 result,
John Stiles3c991fd2021-08-09 14:19:58 -0400584 this->getType(IndexExpression::IndexType(fContext, *type), layout),
585 type->columns(),
John Stiles51d33982021-03-08 09:18:07 -0500586 fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700587 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400588 case Type::TypeKind::kStruct:
John Stiles3c991fd2021-08-09 14:19:58 -0400589 this->writeStruct(*type, layout, result);
ethannicholasb3058bd2016-07-01 08:22:01 -0700590 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400591 case Type::TypeKind::kArray: {
John Stiles3c991fd2021-08-09 14:19:58 -0400592 if (!MemoryLayout::LayoutIsSupported(*type)) {
Brian Osmancc914522021-09-24 18:58:37 +0000593 fContext.fErrors->error(type->fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400594 "type '" + type->name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400595 return this->nextId(nullptr);
John Stiles21f5f452020-11-30 09:57:59 -0500596 }
John Stiles3c991fd2021-08-09 14:19:58 -0400597 if (type->columns() > 0) {
598 SpvId typeId = this->getType(type->componentType(), layout);
Brian Osmancc914522021-09-24 18:58:37 +0000599 Literal countLiteral(/*offset=*/-1, type->columns(),
John Stiles7591d4b2021-09-13 13:32:06 -0400600 fContext.fTypes.fInt.get());
601 SpvId countId = this->writeLiteral(countLiteral);
John Stilesb5db4822021-01-21 13:04:40 -0500602 this->writeInstruction(SpvOpTypeArray, result, typeId, countId,
603 fConstantBuffer);
Greg Daniel64773e62016-11-22 09:44:03 -0500604 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
John Stiles3c991fd2021-08-09 14:19:58 -0400605 (int32_t) layout.stride(*type),
ethannicholas8ac838d2016-11-22 08:39:36 -0800606 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700607 } else {
John Stiles5570c512020-11-19 17:58:07 -0500608 // We shouldn't have any runtime-sized arrays right now
Brian Osmancc914522021-09-24 18:58:37 +0000609 fContext.fErrors->error(type->fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -0400610 "runtime-sized arrays are not supported in SPIR-V");
Greg Daniel64773e62016-11-22 09:44:03 -0500611 this->writeInstruction(SpvOpTypeRuntimeArray, result,
John Stiles3c991fd2021-08-09 14:19:58 -0400612 this->getType(type->componentType(), layout),
ethannicholas8ac838d2016-11-22 08:39:36 -0800613 fConstantBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400614 this->writeInstruction(SpvOpDecorate, result, SpvDecorationArrayStride,
John Stiles3c991fd2021-08-09 14:19:58 -0400615 (int32_t) layout.stride(*type),
Ethan Nicholas0dd30d92017-05-01 16:57:07 -0400616 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700617 }
618 break;
619 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400620 case Type::TypeKind::kSampler: {
Greg Daniel64773e62016-11-22 09:44:03 -0500621 SpvId image = result;
John Stiles3c991fd2021-08-09 14:19:58 -0400622 if (SpvDimSubpassData != type->dimensions()) {
623 image = this->getType(type->textureType(), layout);
Greg Daniel64773e62016-11-22 09:44:03 -0500624 }
John Stiles3c991fd2021-08-09 14:19:58 -0400625 if (SpvDimBuffer == type->dimensions()) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400626 fCapabilities |= (((uint64_t) 1) << SpvCapabilitySampledBuffer);
627 }
John Stiles3c991fd2021-08-09 14:19:58 -0400628 if (SpvDimSubpassData != type->dimensions()) {
Greg Daniel64773e62016-11-22 09:44:03 -0500629 this->writeInstruction(SpvOpTypeSampledImage, result, image, fConstantBuffer);
630 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700631 break;
632 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400633 case Type::TypeKind::kSeparateSampler: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400634 this->writeInstruction(SpvOpTypeSampler, result, fConstantBuffer);
635 break;
636 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400637 case Type::TypeKind::kTexture: {
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400638 this->writeInstruction(SpvOpTypeImage, result,
John Stiles54e7c052021-01-11 14:22:36 -0500639 this->getType(*fContext.fTypes.fFloat, layout),
John Stiles3c991fd2021-08-09 14:19:58 -0400640 type->dimensions(), type->isDepth(),
641 type->isArrayedTexture(), type->isMultisampled(),
642 type->isSampled() ? 1 : 2, SpvImageFormatUnknown,
643 fConstantBuffer);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400644 fImageTypeMap[key] = result;
645 break;
646 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700647 default:
John Stiles3c991fd2021-08-09 14:19:58 -0400648 if (type->isVoid()) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700649 this->writeInstruction(SpvOpTypeVoid, result, fConstantBuffer);
650 } else {
John Stiles3c991fd2021-08-09 14:19:58 -0400651 SkDEBUGFAILF("invalid type: %s", type->description().c_str());
ethannicholasb3058bd2016-07-01 08:22:01 -0700652 }
Ethan Nicholasb13f3692021-09-10 16:49:42 -0400653 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700654 }
ethannicholas8ac838d2016-11-22 08:39:36 -0800655 fTypeMap[key] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -0700656 return result;
657 }
658 return entry->second;
659}
660
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400661SpvId SPIRVCodeGenerator::getImageType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400662 SkASSERT(type.typeKind() == Type::TypeKind::kSampler);
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400663 this->getType(type);
664 String key = type.name() + to_string((int) fDefaultLayout.fStd);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400665 SkASSERT(fImageTypeMap.find(key) != fImageTypeMap.end());
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400666 return fImageTypeMap[key];
667}
668
ethannicholasd598f792016-07-25 10:08:54 -0700669SpvId SPIRVCodeGenerator::getFunctionType(const FunctionDeclaration& function) {
Ethan Nicholased84b732020-10-08 11:45:44 -0400670 String key = to_string(this->getType(function.returnType())) + "(";
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400671 String separator;
Brian Osman5bf3e202020-10-13 10:34:18 -0400672 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholased84b732020-10-08 11:45:44 -0400673 for (size_t i = 0; i < parameters.size(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700674 key += separator;
675 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400676 key += to_string(this->getType(parameters[i]->type()));
ethannicholasb3058bd2016-07-01 08:22:01 -0700677 }
678 key += ")";
679 auto entry = fTypeMap.find(key);
680 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400681 SpvId result = this->nextId(nullptr);
Ethan Nicholased84b732020-10-08 11:45:44 -0400682 int32_t length = 3 + (int32_t) parameters.size();
683 SpvId returnType = this->getType(function.returnType());
ethannicholasb3058bd2016-07-01 08:22:01 -0700684 std::vector<SpvId> parameterTypes;
Ethan Nicholased84b732020-10-08 11:45:44 -0400685 for (size_t i = 0; i < parameters.size(); i++) {
Greg Daniel64773e62016-11-22 09:44:03 -0500686 // glslang seems to treat all function arguments as pointers whether they need to be or
687 // not. I was initially puzzled by this until I ran bizarre failures with certain
688 // patterns of function calls and control constructs, as exemplified by this minimal
ethannicholasb3058bd2016-07-01 08:22:01 -0700689 // failure case:
690 //
691 // void sphere(float x) {
692 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500693 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700694 // void map() {
695 // sphere(1.0);
696 // }
Greg Daniel64773e62016-11-22 09:44:03 -0500697 //
ethannicholasb3058bd2016-07-01 08:22:01 -0700698 // void main() {
699 // for (int i = 0; i < 1; i++) {
700 // map();
701 // }
702 // }
703 //
Greg Daniel64773e62016-11-22 09:44:03 -0500704 // As of this writing, compiling this in the "obvious" way (with sphere taking a float)
705 // crashes. Making it take a float* and storing the argument in a temporary variable,
ethannicholasb3058bd2016-07-01 08:22:01 -0700706 // as glslang does, fixes it. It's entirely possible I simply missed whichever part of
707 // the spec makes this make sense.
John Stiles07367122021-09-08 13:12:26 -0400708 parameterTypes.push_back(this->getPointerType(parameters[i]->type(),
709 SpvStorageClassFunction));
ethannicholasb3058bd2016-07-01 08:22:01 -0700710 }
711 this->writeOpCode(SpvOpTypeFunction, length, fConstantBuffer);
712 this->writeWord(result, fConstantBuffer);
713 this->writeWord(returnType, fConstantBuffer);
714 for (SpvId id : parameterTypes) {
715 this->writeWord(id, fConstantBuffer);
716 }
717 fTypeMap[key] = result;
718 return result;
719 }
720 return entry->second;
721}
722
ethannicholas8ac838d2016-11-22 08:39:36 -0800723SpvId SPIRVCodeGenerator::getPointerType(const Type& type, SpvStorageClass_ storageClass) {
724 return this->getPointerType(type, fDefaultLayout, storageClass);
725}
726
Ethan Nicholasf7b88202017-09-18 14:10:39 -0400727SpvId SPIRVCodeGenerator::getPointerType(const Type& rawType, const MemoryLayout& layout,
ethannicholasb3058bd2016-07-01 08:22:01 -0700728 SpvStorageClass_ storageClass) {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400729 const Type& type = this->getActualType(rawType);
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500730 String key = type.displayName() + "*" + to_string(layout.fStd) + to_string(storageClass);
ethannicholasb3058bd2016-07-01 08:22:01 -0700731 auto entry = fTypeMap.find(key);
732 if (entry == fTypeMap.end()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400733 SpvId result = this->nextId(nullptr);
Greg Daniel64773e62016-11-22 09:44:03 -0500734 this->writeInstruction(SpvOpTypePointer, result, storageClass,
ethannicholasd598f792016-07-25 10:08:54 -0700735 this->getType(type), fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -0700736 fTypeMap[key] = result;
737 return result;
738 }
739 return entry->second;
740}
741
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400742SpvId SPIRVCodeGenerator::writeExpression(const Expression& expr, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400743 switch (expr.kind()) {
744 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400745 return this->writeBinaryExpression(expr.as<BinaryExpression>(), out);
John Stilese3ae9682021-08-05 10:35:01 -0400746 case Expression::Kind::kConstructorArrayCast:
747 return this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), out);
John Stiles7384b372021-04-01 13:48:15 -0400748 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400749 case Expression::Kind::kConstructorStruct:
750 return this->writeCompositeConstructor(expr.asAnyConstructor(), out);
John Stilese1182782021-03-30 22:09:37 -0400751 case Expression::Kind::kConstructorDiagonalMatrix:
752 return this->writeConstructorDiagonalMatrix(expr.as<ConstructorDiagonalMatrix>(), out);
John Stiles5abb9e12021-04-06 13:47:19 -0400753 case Expression::Kind::kConstructorMatrixResize:
754 return this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(), out);
John Stilesfd7252f2021-04-04 22:24:40 -0400755 case Expression::Kind::kConstructorScalarCast:
756 return this->writeConstructorScalarCast(expr.as<ConstructorScalarCast>(), out);
John Stiles2938eea2021-04-01 18:58:25 -0400757 case Expression::Kind::kConstructorSplat:
758 return this->writeConstructorSplat(expr.as<ConstructorSplat>(), out);
John Stiles8cad6372021-04-07 12:31:13 -0400759 case Expression::Kind::kConstructorCompound:
760 return this->writeConstructorCompound(expr.as<ConstructorCompound>(), out);
761 case Expression::Kind::kConstructorCompoundCast:
762 return this->writeConstructorCompoundCast(expr.as<ConstructorCompoundCast>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400763 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400764 return this->writeFieldAccess(expr.as<FieldAccess>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400765 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400766 return this->writeFunctionCall(expr.as<FunctionCall>(), out);
John Stiles7591d4b2021-09-13 13:32:06 -0400767 case Expression::Kind::kLiteral:
768 return this->writeLiteral(expr.as<Literal>());
Ethan Nicholase6592142020-09-08 10:22:09 -0400769 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400770 return this->writePrefixExpression(expr.as<PrefixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400771 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400772 return this->writePostfixExpression(expr.as<PostfixExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400773 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400774 return this->writeSwizzle(expr.as<Swizzle>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400775 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400776 return this->writeVariableReference(expr.as<VariableReference>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400777 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400778 return this->writeTernaryExpression(expr.as<TernaryExpression>(), out);
Ethan Nicholase6592142020-09-08 10:22:09 -0400779 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400780 return this->writeIndexExpression(expr.as<IndexExpression>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700781 default:
John Stileseada7bc2021-02-02 16:29:32 -0500782 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500783 break;
ethannicholasb3058bd2016-07-01 08:22:01 -0700784 }
785 return -1;
786}
787
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400788SpvId SPIRVCodeGenerator::writeIntrinsicCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400789 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -0400790 auto intrinsic = fIntrinsicMap.find(function.intrinsicKind());
John Stiles93e661a2020-12-08 16:17:00 -0500791 if (intrinsic == fIntrinsicMap.end()) {
Brian Osmancc914522021-09-24 18:58:37 +0000792 fContext.fErrors->error(c.fOffset, "unsupported intrinsic '" + function.description() +
793 "'");
John Stiles93e661a2020-12-08 16:17:00 -0500794 return -1;
795 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700796 int32_t intrinsicId;
John Stiles89ac7c22020-12-30 17:47:31 -0500797 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400798 if (arguments.size() > 0) {
799 const Type& type = arguments[0]->type();
John Stilesaaac4e42021-05-06 14:08:28 -0400800 if (std::get<0>(intrinsic->second) == kSpecial_IntrinsicOpcodeKind ||
801 is_float(fContext, type)) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400802 intrinsicId = std::get<1>(intrinsic->second);
803 } else if (is_signed(fContext, type)) {
804 intrinsicId = std::get<2>(intrinsic->second);
805 } else if (is_unsigned(fContext, type)) {
806 intrinsicId = std::get<3>(intrinsic->second);
807 } else if (is_bool(fContext, type)) {
808 intrinsicId = std::get<4>(intrinsic->second);
809 } else {
810 intrinsicId = std::get<1>(intrinsic->second);
811 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700812 } else {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400813 intrinsicId = std::get<1>(intrinsic->second);
ethannicholasb3058bd2016-07-01 08:22:01 -0700814 }
815 switch (std::get<0>(intrinsic->second)) {
John Stilesaaac4e42021-05-06 14:08:28 -0400816 case kGLSL_STD_450_IntrinsicOpcodeKind: {
Ethan Nicholas7f015882021-03-23 14:16:52 -0400817 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400818 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400819 std::vector<TempVar> tempVars;
820 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400821 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -0400822 if (is_out(function.parameters()[i]->modifiers())) {
823 argumentIds.push_back(
824 this->writeFunctionCallArgument(*arguments[i],
825 function.parameters()[i]->modifiers(),
826 &tempVars,
827 out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400828 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400829 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400830 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700831 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400832 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400833 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700834 this->writeWord(result, out);
835 this->writeWord(fGLSLExtendedInstructions, out);
836 this->writeWord(intrinsicId, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400837 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700838 this->writeWord(id, out);
839 }
John Stiles07367122021-09-08 13:12:26 -0400840 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700841 return result;
842 }
John Stilesaaac4e42021-05-06 14:08:28 -0400843 case kSPIRV_IntrinsicOpcodeKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500844 // GLSL supports dot(float, float), but SPIR-V does not. Convert it to FMul
John Stiles9aeed132020-11-24 17:36:06 -0500845 if (intrinsicId == SpvOpDot && arguments[0]->type().isScalar()) {
Brian Osman46787d52020-11-24 14:18:23 -0500846 intrinsicId = SpvOpFMul;
847 }
Ethan Nicholas7f015882021-03-23 14:16:52 -0400848 SpvId result = this->nextId(&c.type());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400849 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400850 std::vector<TempVar> tempVars;
851 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400852 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -0400853 if (is_out(function.parameters()[i]->modifiers())) {
854 argumentIds.push_back(
855 this->writeFunctionCallArgument(*arguments[i],
856 function.parameters()[i]->modifiers(),
857 &tempVars,
858 out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400859 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400860 argumentIds.push_back(this->writeExpression(*arguments[i], out));
Ethan Nicholas8f7e28f2018-03-26 14:24:27 -0400861 }
ethannicholasb3058bd2016-07-01 08:22:01 -0700862 }
John Stiles2558c462021-03-16 17:49:20 -0400863 if (!c.type().isVoid()) {
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400864 this->writeOpCode((SpvOp_) intrinsicId, 3 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400865 this->writeWord(this->getType(c.type()), out);
Ethan Nicholasbb155e22017-07-24 10:05:09 -0400866 this->writeWord(result, out);
867 } else {
868 this->writeOpCode((SpvOp_) intrinsicId, 1 + (int32_t) arguments.size(), out);
869 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400870 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700871 this->writeWord(id, out);
872 }
John Stiles07367122021-09-08 13:12:26 -0400873 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700874 return result;
875 }
John Stilesaaac4e42021-05-06 14:08:28 -0400876 case kSpecial_IntrinsicOpcodeKind:
ethannicholasb3058bd2016-07-01 08:22:01 -0700877 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId, out);
878 default:
Brian Osmancc914522021-09-24 18:58:37 +0000879 fContext.fErrors->error(c.fOffset, "unsupported intrinsic '" + function.description() +
880 "'");
John Stiles93e661a2020-12-08 16:17:00 -0500881 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -0700882 }
883}
884
Brian Salomond8d85b92021-07-07 09:41:17 -0400885SpvId SPIRVCodeGenerator::vectorize(const Expression& arg, int vectorSize, OutputStream& out) {
886 SkASSERT(vectorSize >= 1 && vectorSize <= 4);
887 const Type& argType = arg.type();
888 SpvId raw = this->writeExpression(arg, out);
889 if (argType.isScalar()) {
890 if (vectorSize == 1) {
891 return raw;
892 }
893 SpvId vector = this->nextId(&argType);
894 this->writeOpCode(SpvOpCompositeConstruct, 3 + vectorSize, out);
895 this->writeWord(this->getType(argType.toCompound(fContext, vectorSize, 1)), out);
896 this->writeWord(vector, out);
897 for (int i = 0; i < vectorSize; i++) {
898 this->writeWord(raw, out);
899 }
900 return vector;
901 } else {
902 SkASSERT(vectorSize == argType.columns());
903 return raw;
904 }
905}
906
John Stiles8e3b6be2020-10-13 11:14:08 -0400907std::vector<SpvId> SPIRVCodeGenerator::vectorize(const ExpressionArray& args, OutputStream& out) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400908 int vectorSize = 1;
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500909 for (const auto& a : args) {
John Stiles9aeed132020-11-24 17:36:06 -0500910 if (a->type().isVector()) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400911 if (vectorSize > 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400912 SkASSERT(a->type().columns() == vectorSize);
Brian Salomond8d85b92021-07-07 09:41:17 -0400913 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400914 vectorSize = a->type().columns();
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500915 }
916 }
917 }
918 std::vector<SpvId> result;
John Stiles8e3b6be2020-10-13 11:14:08 -0400919 result.reserve(args.size());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400920 for (const auto& arg : args) {
Brian Salomond8d85b92021-07-07 09:41:17 -0400921 result.push_back(this->vectorize(*arg, vectorSize, out));
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500922 }
923 return result;
924}
925
926void SPIRVCodeGenerator::writeGLSLExtendedInstruction(const Type& type, SpvId id, SpvId floatInst,
927 SpvId signedInst, SpvId unsignedInst,
928 const std::vector<SpvId>& args,
929 OutputStream& out) {
930 this->writeOpCode(SpvOpExtInst, 5 + args.size(), out);
931 this->writeWord(this->getType(type), out);
932 this->writeWord(id, out);
933 this->writeWord(fGLSLExtendedInstructions, out);
934
935 if (is_float(fContext, type)) {
936 this->writeWord(floatInst, out);
937 } else if (is_signed(fContext, type)) {
938 this->writeWord(signedInst, out);
939 } else if (is_unsigned(fContext, type)) {
940 this->writeWord(unsignedInst, out);
941 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400942 SkASSERT(false);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -0500943 }
944 for (SpvId a : args) {
945 this->writeWord(a, out);
946 }
947}
948
Greg Daniel64773e62016-11-22 09:44:03 -0500949SpvId SPIRVCodeGenerator::writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind,
Ethan Nicholas0df1b042017-03-31 13:56:23 -0400950 OutputStream& out) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400951 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400952 const Type& callType = c.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -0400953 SpvId result = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -0700954 switch (kind) {
955 case kAtan_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400956 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -0400957 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400958 for (const std::unique_ptr<Expression>& arg : arguments) {
959 argumentIds.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -0700960 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400961 this->writeOpCode(SpvOpExtInst, 5 + (int32_t) argumentIds.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400962 this->writeWord(this->getType(callType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -0700963 this->writeWord(result, out);
964 this->writeWord(fGLSLExtendedInstructions, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400965 this->writeWord(argumentIds.size() == 2 ? GLSLstd450Atan2 : GLSLstd450Atan, out);
966 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -0700967 this->writeWord(id, out);
968 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400969 break;
970 }
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400971 case kSampledImage_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400972 SkASSERT(arguments.size() == 2);
973 SpvId img = this->writeExpression(*arguments[0], out);
974 SpvId sampler = this->writeExpression(*arguments[1], out);
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400975 this->writeInstruction(SpvOpSampledImage,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400976 this->getType(callType),
Stephen Whiteff5d7a22019-07-26 17:42:06 -0400977 result,
978 img,
979 sampler,
980 out);
981 break;
982 }
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400983 case kSubpassLoad_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400984 SpvId img = this->writeExpression(*arguments[0], out);
John Stiles8e3b6be2020-10-13 11:14:08 -0400985 ExpressionArray args;
John Stilesf4bda742020-10-14 16:57:41 -0400986 args.reserve_back(2);
Brian Osmancc914522021-09-24 18:58:37 +0000987 args.push_back(Literal::MakeInt(fContext, /*offset=*/-1, /*value=*/0));
988 args.push_back(Literal::MakeInt(fContext, /*offset=*/-1, /*value=*/0));
989 ConstructorCompound ctor(/*offset=*/-1, *fContext.fTypes.fInt2, std::move(args));
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400990 SpvId coords = this->writeConstantVector(ctor);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400991 if (arguments.size() == 1) {
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400992 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400993 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -0400994 result,
995 img,
996 coords,
997 out);
998 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400999 SkASSERT(arguments.size() == 2);
1000 SpvId sample = this->writeExpression(*arguments[1], out);
Ethan Nicholas0187ae62017-05-03 11:03:44 -04001001 this->writeInstruction(SpvOpImageRead,
Ethan Nicholas30d30222020-09-11 12:27:26 -04001002 this->getType(callType),
Ethan Nicholas0187ae62017-05-03 11:03:44 -04001003 result,
1004 img,
1005 coords,
1006 SpvImageOperandsSampleMask,
1007 sample,
1008 out);
1009 }
1010 break;
1011 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001012 case kTexture_SpecialIntrinsic: {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001013 SpvOp_ op = SpvOpImageSampleImplicitLod;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001014 const Type& arg1Type = arguments[1]->type();
1015 switch (arguments[0]->type().dimensions()) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001016 case SpvDim1D:
John Stiles54e7c052021-01-11 14:22:36 -05001017 if (arg1Type == *fContext.fTypes.fFloat2) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001018 op = SpvOpImageSampleProjImplicitLod;
1019 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001020 SkASSERT(arg1Type == *fContext.fTypes.fFloat);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001021 }
1022 break;
1023 case SpvDim2D:
John Stiles54e7c052021-01-11 14:22:36 -05001024 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001025 op = SpvOpImageSampleProjImplicitLod;
1026 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001027 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001028 }
1029 break;
1030 case SpvDim3D:
John Stiles54e7c052021-01-11 14:22:36 -05001031 if (arg1Type == *fContext.fTypes.fFloat4) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001032 op = SpvOpImageSampleProjImplicitLod;
1033 } else {
John Stiles54e7c052021-01-11 14:22:36 -05001034 SkASSERT(arg1Type == *fContext.fTypes.fFloat3);
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001035 }
1036 break;
1037 case SpvDimCube: // fall through
1038 case SpvDimRect: // fall through
1039 case SpvDimBuffer: // fall through
1040 case SpvDimSubpassData:
1041 break;
1042 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001043 SpvId type = this->getType(callType);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001044 SpvId sampler = this->writeExpression(*arguments[0], out);
1045 SpvId uv = this->writeExpression(*arguments[1], out);
1046 if (arguments.size() == 3) {
Ethan Nicholas2b3dab62016-11-28 12:03:26 -05001047 this->writeInstruction(op, type, result, sampler, uv,
ethannicholasb3058bd2016-07-01 08:22:01 -07001048 SpvImageOperandsBiasMask,
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001049 this->writeExpression(*arguments[2], out),
ethannicholasb3058bd2016-07-01 08:22:01 -07001050 out);
1051 } else {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001052 SkASSERT(arguments.size() == 2);
John Stiles270cec22021-02-17 12:59:36 -05001053 if (fProgram.fConfig->fSettings.fSharpenTextures) {
Brian Osmancc914522021-09-24 18:58:37 +00001054 Literal lodBias(/*offset=*/-1, /*value=*/-0.5, fContext.fTypes.fFloat.get());
Brian Osman8a83ca42018-02-12 14:32:17 -05001055 this->writeInstruction(op, type, result, sampler, uv,
1056 SpvImageOperandsBiasMask,
John Stiles7591d4b2021-09-13 13:32:06 -04001057 this->writeLiteral(lodBias),
Brian Osman8a83ca42018-02-12 14:32:17 -05001058 out);
1059 } else {
1060 this->writeInstruction(op, type, result, sampler, uv,
1061 out);
1062 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001063 }
1064 break;
1065 }
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001066 case kMod_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001067 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001068 SkASSERT(args.size() == 2);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001069 const Type& operandType = arguments[0]->type();
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001070 SpvOp_ op;
1071 if (is_float(fContext, operandType)) {
1072 op = SpvOpFMod;
1073 } else if (is_signed(fContext, operandType)) {
1074 op = SpvOpSMod;
1075 } else if (is_unsigned(fContext, operandType)) {
1076 op = SpvOpUMod;
1077 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001078 SkASSERT(false);
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001079 return 0;
1080 }
1081 this->writeOpCode(op, 5, out);
1082 this->writeWord(this->getType(operandType), out);
1083 this->writeWord(result, out);
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001084 this->writeWord(args[0], out);
1085 this->writeWord(args[1], out);
1086 break;
1087 }
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001088 case kDFdy_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001089 SpvId fn = this->writeExpression(*arguments[0], out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001090 this->writeOpCode(SpvOpDPdy, 4, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001091 this->writeWord(this->getType(callType), out);
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001092 this->writeWord(result, out);
1093 this->writeWord(fn, out);
Brian Osmancc914522021-09-24 18:58:37 +00001094 this->addRTFlipUniform(c.fOffset);
Brian Salomond8d85b92021-07-07 09:41:17 -04001095 using namespace dsl;
Brian Osmancc914522021-09-24 18:58:37 +00001096 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04001097 SKSL_RTFLIP_NAME));
1098 SpvId rtFlipY = this->vectorize(*rtFlip.y().release(), callType.columns(), out);
1099 SpvId flipped = this->nextId(&callType);
1100 this->writeInstruction(SpvOpFMul, this->getType(callType), flipped, result, rtFlipY,
1101 out);
1102 result = flipped;
Chris Daltonb8af5ad2019-02-25 14:54:21 -07001103 break;
1104 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001105 case kClamp_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001106 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001107 SkASSERT(args.size() == 3);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001108 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001109 GLSLstd450UClamp, args, out);
1110 break;
1111 }
1112 case kMax_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001113 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001114 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001115 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMax, GLSLstd450SMax,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001116 GLSLstd450UMax, args, out);
1117 break;
1118 }
1119 case kMin_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001120 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001121 SkASSERT(args.size() == 2);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001122 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMin, GLSLstd450SMin,
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001123 GLSLstd450UMin, args, out);
1124 break;
1125 }
1126 case kMix_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001127 std::vector<SpvId> args = this->vectorize(arguments, out);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001128 SkASSERT(args.size() == 3);
John Stilescc2d9cc2021-07-09 17:38:41 -04001129 if (arguments[2]->type().componentType().isBoolean()) {
1130 // Use OpSelect to implement Boolean mix().
1131 SpvId falseId = this->writeExpression(*arguments[0], out);
1132 SpvId trueId = this->writeExpression(*arguments[1], out);
1133 SpvId conditionId = this->writeExpression(*arguments[2], out);
1134 this->writeInstruction(SpvOpSelect, this->getType(arguments[0]->type()), result,
1135 conditionId, trueId, falseId, out);
1136 } else {
1137 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FMix, SpvOpUndef,
1138 SpvOpUndef, args, out);
1139 }
Ethan Nicholas0fc07f92018-02-27 15:25:47 -05001140 break;
Ethan Nicholas70a44b22017-11-30 09:09:16 -05001141 }
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001142 case kSaturate_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001143 SkASSERT(arguments.size() == 1);
John Stiles8e3b6be2020-10-13 11:14:08 -04001144 ExpressionArray finalArgs;
John Stilesf4bda742020-10-14 16:57:41 -04001145 finalArgs.reserve_back(3);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001146 finalArgs.push_back(arguments[0]->clone());
Brian Osmancc914522021-09-24 18:58:37 +00001147 finalArgs.push_back(Literal::MakeFloat(fContext, /*offset=*/-1, /*value=*/0));
1148 finalArgs.push_back(Literal::MakeFloat(fContext, /*offset=*/-1, /*value=*/1));
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001149 std::vector<SpvId> spvArgs = this->vectorize(finalArgs, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001150 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450FClamp, GLSLstd450SClamp,
Ethan Nicholas12fb9cf2018-08-03 16:16:57 -04001151 GLSLstd450UClamp, spvArgs, out);
1152 break;
1153 }
Brian Osman6ba3be12020-11-13 16:32:52 -05001154 case kSmoothStep_SpecialIntrinsic: {
1155 std::vector<SpvId> args = this->vectorize(arguments, out);
1156 SkASSERT(args.size() == 3);
1157 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450SmoothStep, SpvOpUndef,
1158 SpvOpUndef, args, out);
1159 break;
1160 }
1161 case kStep_SpecialIntrinsic: {
1162 std::vector<SpvId> args = this->vectorize(arguments, out);
1163 SkASSERT(args.size() == 2);
1164 this->writeGLSLExtendedInstruction(callType, result, GLSLstd450Step, SpvOpUndef,
1165 SpvOpUndef, args, out);
1166 break;
1167 }
Brian Osmand1b593f2020-12-28 13:00:46 -05001168 case kMatrixCompMult_SpecialIntrinsic: {
1169 SkASSERT(arguments.size() == 2);
1170 SpvId lhs = this->writeExpression(*arguments[0], out);
1171 SpvId rhs = this->writeExpression(*arguments[1], out);
John Stiles43b593c2021-05-13 22:03:27 -04001172 result = this->writeComponentwiseMatrixBinary(callType, lhs, rhs, SpvOpFMul, out);
Brian Osmand1b593f2020-12-28 13:00:46 -05001173 break;
1174 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001175 }
1176 return result;
1177}
1178
John Stiles07367122021-09-08 13:12:26 -04001179SpvId SPIRVCodeGenerator::writeFunctionCallArgument(const Expression& arg,
1180 const Modifiers& paramModifiers,
1181 std::vector<TempVar>* tempVars,
1182 OutputStream& out) {
1183 // ID of temporary variable that we will use to hold this argument, or 0 if it is being
1184 // passed directly
1185 SpvId tmpVar;
1186 // if we need a temporary var to store this argument, this is the value to store in the var
1187 SpvId tmpValueId = -1;
1188
1189 if (is_out(paramModifiers)) {
1190 std::unique_ptr<LValue> lv = this->getLValue(arg, out);
1191 SpvId ptr = lv->getPointer();
1192 if (ptr != (SpvId) -1 && lv->isMemoryObjectPointer()) {
1193 return ptr;
1194 }
1195
1196 // lvalue cannot simply be read and written via a pointer (e.g. it's a swizzle). We need to
1197 // to use a temp variable.
1198 if (is_in(paramModifiers)) {
1199 tmpValueId = lv->load(out);
1200 }
1201 tmpVar = this->nextId(&arg.type());
1202 tempVars->push_back(TempVar{tmpVar, &arg.type(), std::move(lv)});
1203 } else {
1204 // See getFunctionType for an explanation of why we're always using pointer parameters.
1205 tmpValueId = this->writeExpression(arg, out);
1206 tmpVar = this->nextId(nullptr);
1207 }
1208 this->writeInstruction(SpvOpVariable,
1209 this->getPointerType(arg.type(), SpvStorageClassFunction),
1210 tmpVar,
1211 SpvStorageClassFunction,
1212 fVariableBuffer);
1213 if (tmpValueId != (SpvId)-1) {
1214 this->writeInstruction(SpvOpStore, tmpVar, tmpValueId, out);
1215 }
1216 return tmpVar;
1217}
1218
1219void SPIRVCodeGenerator::copyBackTempVars(const std::vector<TempVar>& tempVars, OutputStream& out) {
1220 for (const TempVar& tempVar : tempVars) {
1221 SpvId load = this->nextId(tempVar.type);
1222 this->writeInstruction(SpvOpLoad, this->getType(*tempVar.type), load, tempVar.spvId, out);
1223 tempVar.lvalue->store(load, out);
1224 }
John Stilesec241542021-02-11 17:50:09 -05001225}
1226
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001227SpvId SPIRVCodeGenerator::writeFunctionCall(const FunctionCall& c, OutputStream& out) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001228 const FunctionDeclaration& function = c.function();
John Stilesaaac4e42021-05-06 14:08:28 -04001229 if (function.isIntrinsic() && !function.definition()) {
John Stiles89ac7c22020-12-30 17:47:31 -05001230 return this->writeIntrinsicCall(c, out);
1231 }
John Stiles8e3b6be2020-10-13 11:14:08 -04001232 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001233 const auto& entry = fFunctionMap.find(&function);
ethannicholasb3058bd2016-07-01 08:22:01 -07001234 if (entry == fFunctionMap.end()) {
Brian Osmancc914522021-09-24 18:58:37 +00001235 fContext.fErrors->error(c.fOffset, "function '" + function.description() +
1236 "' is not defined");
John Stiles89ac7c22020-12-30 17:47:31 -05001237 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001238 }
John Stilesec241542021-02-11 17:50:09 -05001239 // Temp variables are used to write back out-parameters after the function call is complete.
1240 std::vector<TempVar> tempVars;
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001241 std::vector<SpvId> argumentIds;
John Stiles07367122021-09-08 13:12:26 -04001242 argumentIds.reserve(arguments.size());
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001243 for (size_t i = 0; i < arguments.size(); i++) {
John Stiles07367122021-09-08 13:12:26 -04001244 argumentIds.push_back(this->writeFunctionCallArgument(*arguments[i],
1245 function.parameters()[i]->modifiers(),
1246 &tempVars,
1247 out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001248 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001249 SpvId result = this->nextId(nullptr);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001250 this->writeOpCode(SpvOpFunctionCall, 4 + (int32_t) arguments.size(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001251 this->writeWord(this->getType(c.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001252 this->writeWord(result, out);
1253 this->writeWord(entry->second, out);
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001254 for (SpvId id : argumentIds) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001255 this->writeWord(id, out);
1256 }
John Stilesec241542021-02-11 17:50:09 -05001257 // Now that the call is complete, we copy temp out-variables back to their real lvalues.
John Stiles07367122021-09-08 13:12:26 -04001258 this->copyBackTempVars(tempVars, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001259 return result;
1260}
1261
John Stiles2938eea2021-04-01 18:58:25 -04001262SpvId SPIRVCodeGenerator::writeConstantVector(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001263 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001264 SkASSERT(type.isVector() && c.isCompileTimeConstant());
John Stilescd806892021-01-06 13:33:31 -05001265
John Stiles9cfaa4f2021-01-06 17:52:00 -05001266 // Get each of the constructor components as SPIR-V constants.
John Stilescd806892021-01-06 13:33:31 -05001267 SPIRVVectorConstant key{this->getType(type),
1268 /*fValueId=*/{SpvId(-1), SpvId(-1), SpvId(-1), SpvId(-1)}};
John Stiles9cfaa4f2021-01-06 17:52:00 -05001269
John Stiles21a50ec2021-04-06 14:49:36 -04001270 for (int n = 0; n < type.columns(); n++) {
1271 const Expression* expr = c.getConstantSubexpression(n);
1272 if (!expr) {
1273 SkDEBUGFAILF("writeConstantVector: %s not actually constant", c.description().c_str());
1274 return (SpvId)-1;
John Stiles9cfaa4f2021-01-06 17:52:00 -05001275 }
John Stiles21a50ec2021-04-06 14:49:36 -04001276 key.fValueId[n] = this->writeExpression(*expr, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07001277 }
John Stilescd806892021-01-06 13:33:31 -05001278
1279 // Check to see if we've already synthesized this vector constant.
1280 auto [iter, newlyCreated] = fVectorConstants.insert({key, (SpvId)-1});
1281 if (newlyCreated) {
1282 // Emit an OpConstantComposite instruction for this constant.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001283 SpvId result = this->nextId(&type);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001284 this->writeOpCode(SpvOpConstantComposite, 3 + type.columns(), fConstantBuffer);
John Stilescd806892021-01-06 13:33:31 -05001285 this->writeWord(key.fTypeId, fConstantBuffer);
1286 this->writeWord(result, fConstantBuffer);
John Stiles9cfaa4f2021-01-06 17:52:00 -05001287 for (int i = 0; i < type.columns(); i++) {
John Stilescd806892021-01-06 13:33:31 -05001288 this->writeWord(key.fValueId[i], fConstantBuffer);
1289 }
1290 iter->second = result;
1291 }
1292 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07001293}
1294
John Stilesb14a8192021-04-05 11:40:46 -04001295SpvId SPIRVCodeGenerator::castScalarToType(SpvId inputExprId,
1296 const Type& inputType,
1297 const Type& outputType,
1298 OutputStream& out) {
1299 if (outputType.isFloat()) {
1300 return this->castScalarToFloat(inputExprId, inputType, outputType, out);
1301 }
1302 if (outputType.isSigned()) {
1303 return this->castScalarToSignedInt(inputExprId, inputType, outputType, out);
1304 }
1305 if (outputType.isUnsigned()) {
1306 return this->castScalarToUnsignedInt(inputExprId, inputType, outputType, out);
1307 }
1308 if (outputType.isBoolean()) {
1309 return this->castScalarToBoolean(inputExprId, inputType, outputType, out);
1310 }
1311
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001312 fContext.fErrors->error(-1, "unsupported cast: " + inputType.description() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001313 " to " + outputType.description());
John Stilesb14a8192021-04-05 11:40:46 -04001314 return inputExprId;
1315}
1316
John Stilesfd7252f2021-04-04 22:24:40 -04001317SpvId SPIRVCodeGenerator::writeFloatConstructor(const AnyConstructor& c, OutputStream& out) {
1318 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001319 SkASSERT(c.type().isFloat());
John Stilesfd7252f2021-04-04 22:24:40 -04001320 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001321 SpvId expressionId = this->writeExpression(ctorExpr, out);
1322 return this->castScalarToFloat(expressionId, ctorExpr.type(), c.type(), out);
1323}
1324
1325SpvId SPIRVCodeGenerator::castScalarToFloat(SpvId inputId, const Type& inputType,
1326 const Type& outputType, OutputStream& out) {
1327 // Casting a float to float is a no-op.
1328 if (inputType.isFloat()) {
1329 return inputId;
1330 }
1331
1332 // Given the input type, generate the appropriate instruction to cast to float.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001333 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001334 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001335 // Use OpSelect to convert the boolean argument to a literal 1.0 or 0.0.
Brian Osmancc914522021-09-24 18:58:37 +00001336 Literal one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001337 const SpvId oneID = this->writeLiteral(one);
Brian Osmancc914522021-09-24 18:58:37 +00001338 Literal zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001339 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001340 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1341 inputId, oneID, zeroID, out);
1342 } else if (inputType.isSigned()) {
1343 this->writeInstruction(SpvOpConvertSToF, this->getType(outputType), result, inputId, out);
1344 } else if (inputType.isUnsigned()) {
1345 this->writeInstruction(SpvOpConvertUToF, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001346 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001347 SkDEBUGFAILF("unsupported type for float typecast: %s", inputType.description().c_str());
1348 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001349 }
1350 return result;
1351}
1352
John Stilesfd7252f2021-04-04 22:24:40 -04001353SpvId SPIRVCodeGenerator::writeIntConstructor(const AnyConstructor& c, OutputStream& out) {
1354 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001355 SkASSERT(c.type().isSigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001356 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001357 SpvId expressionId = this->writeExpression(ctorExpr, out);
1358 return this->castScalarToSignedInt(expressionId, ctorExpr.type(), c.type(), out);
1359}
1360
1361SpvId SPIRVCodeGenerator::castScalarToSignedInt(SpvId inputId, const Type& inputType,
1362 const Type& outputType, OutputStream& out) {
1363 // Casting a signed int to signed int is a no-op.
1364 if (inputType.isSigned()) {
1365 return inputId;
1366 }
1367
1368 // Given the input type, generate the appropriate instruction to cast to signed int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001369 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001370 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001371 // Use OpSelect to convert the boolean argument to a literal 1 or 0.
Brian Osmancc914522021-09-24 18:58:37 +00001372 Literal one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001373 const SpvId oneID = this->writeLiteral(one);
Brian Osmancc914522021-09-24 18:58:37 +00001374 Literal zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001375 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001376 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1377 inputId, oneID, zeroID, out);
1378 } else if (inputType.isFloat()) {
1379 this->writeInstruction(SpvOpConvertFToS, this->getType(outputType), result, inputId, out);
1380 } else if (inputType.isUnsigned()) {
1381 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
1382 } else {
1383 SkDEBUGFAILF("unsupported type for signed int typecast: %s",
1384 inputType.description().c_str());
1385 return (SpvId)-1;
ethannicholasb3058bd2016-07-01 08:22:01 -07001386 }
1387 return result;
1388}
1389
John Stilesfd7252f2021-04-04 22:24:40 -04001390SpvId SPIRVCodeGenerator::writeUIntConstructor(const AnyConstructor& c, OutputStream& out) {
1391 SkASSERT(c.argumentSpan().size() == 1);
John Stilesd9d52712021-01-13 17:15:02 -05001392 SkASSERT(c.type().isUnsigned());
John Stilesfd7252f2021-04-04 22:24:40 -04001393 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesd9d52712021-01-13 17:15:02 -05001394 SpvId expressionId = this->writeExpression(ctorExpr, out);
1395 return this->castScalarToUnsignedInt(expressionId, ctorExpr.type(), c.type(), out);
1396}
1397
1398SpvId SPIRVCodeGenerator::castScalarToUnsignedInt(SpvId inputId, const Type& inputType,
1399 const Type& outputType, OutputStream& out) {
1400 // Casting an unsigned int to unsigned int is a no-op.
1401 if (inputType.isUnsigned()) {
1402 return inputId;
1403 }
1404
John Stiles48c28842021-01-14 11:05:03 -05001405 // Given the input type, generate the appropriate instruction to cast to unsigned int.
Ethan Nicholas7f015882021-03-23 14:16:52 -04001406 SpvId result = this->nextId(&outputType);
John Stilesd9d52712021-01-13 17:15:02 -05001407 if (inputType.isBoolean()) {
John Stilesba4b0e92021-01-05 13:55:39 -05001408 // Use OpSelect to convert the boolean argument to a literal 1u or 0u.
Brian Osmancc914522021-09-24 18:58:37 +00001409 Literal one(/*offset=*/-1, /*value=*/1, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001410 const SpvId oneID = this->writeLiteral(one);
Brian Osmancc914522021-09-24 18:58:37 +00001411 Literal zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001412 const SpvId zeroID = this->writeLiteral(zero);
John Stilesd9d52712021-01-13 17:15:02 -05001413 this->writeInstruction(SpvOpSelect, this->getType(outputType), result,
1414 inputId, oneID, zeroID, out);
1415 } else if (inputType.isFloat()) {
1416 this->writeInstruction(SpvOpConvertFToU, this->getType(outputType), result, inputId, out);
1417 } else if (inputType.isSigned()) {
1418 this->writeInstruction(SpvOpBitcast, this->getType(outputType), result, inputId, out);
Ethan Nicholasf7b88202017-09-18 14:10:39 -04001419 } else {
John Stilesd9d52712021-01-13 17:15:02 -05001420 SkDEBUGFAILF("unsupported type for unsigned int typecast: %s",
1421 inputType.description().c_str());
1422 return (SpvId)-1;
Ethan Nicholas925f52d2017-07-19 10:42:50 -04001423 }
1424 return result;
1425}
1426
John Stilesfd7252f2021-04-04 22:24:40 -04001427SpvId SPIRVCodeGenerator::writeBooleanConstructor(const AnyConstructor& c, OutputStream& out) {
1428 SkASSERT(c.argumentSpan().size() == 1);
John Stilesa60fb172021-01-14 11:06:20 -05001429 SkASSERT(c.type().isBoolean());
John Stilesfd7252f2021-04-04 22:24:40 -04001430 const Expression& ctorExpr = *c.argumentSpan().front();
John Stilesa60fb172021-01-14 11:06:20 -05001431 SpvId expressionId = this->writeExpression(ctorExpr, out);
1432 return this->castScalarToBoolean(expressionId, ctorExpr.type(), c.type(), out);
1433}
1434
John Stiles48c28842021-01-14 11:05:03 -05001435SpvId SPIRVCodeGenerator::castScalarToBoolean(SpvId inputId, const Type& inputType,
1436 const Type& outputType, OutputStream& out) {
1437 // Casting a bool to bool is a no-op.
1438 if (inputType.isBoolean()) {
1439 return inputId;
1440 }
1441
1442 // Given the input type, generate the appropriate instruction to cast to bool.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001443 SpvId result = this->nextId(nullptr);
John Stiles48c28842021-01-14 11:05:03 -05001444 if (inputType.isSigned()) {
1445 // Synthesize a boolean result by comparing the input against a signed zero literal.
Brian Osmancc914522021-09-24 18:58:37 +00001446 Literal zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001447 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001448 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1449 inputId, zeroID, out);
1450 } else if (inputType.isUnsigned()) {
1451 // Synthesize a boolean result by comparing the input against an unsigned zero literal.
Brian Osmancc914522021-09-24 18:58:37 +00001452 Literal zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fUInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001453 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001454 this->writeInstruction(SpvOpINotEqual, this->getType(outputType), result,
1455 inputId, zeroID, out);
1456 } else if (inputType.isFloat()) {
1457 // Synthesize a boolean result by comparing the input against a floating-point zero literal.
Brian Osmancc914522021-09-24 18:58:37 +00001458 Literal zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001459 const SpvId zeroID = this->writeLiteral(zero);
John Stiles48c28842021-01-14 11:05:03 -05001460 this->writeInstruction(SpvOpFUnordNotEqual, this->getType(outputType), result,
1461 inputId, zeroID, out);
1462 } else {
1463 SkDEBUGFAILF("unsupported type for boolean typecast: %s", inputType.description().c_str());
1464 return (SpvId)-1;
1465 }
1466 return result;
1467}
1468
Ethan Nicholas84645e32017-02-09 13:57:14 -05001469void SPIRVCodeGenerator::writeUniformScaleMatrix(SpvId id, SpvId diagonal, const Type& type,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001470 OutputStream& out) {
Brian Osmancc914522021-09-24 18:58:37 +00001471 Literal zero(/*offset=*/-1, /*value=*/0, fContext.fTypes.fFloat.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001472 SpvId zeroId = this->writeLiteral(zero);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001473 std::vector<SpvId> columnIds;
John Stiles392d8292021-04-09 12:14:03 -04001474 columnIds.reserve(type.columns());
Ethan Nicholas84645e32017-02-09 13:57:14 -05001475 for (int column = 0; column < type.columns(); column++) {
1476 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.rows(),
1477 out);
John Stiles392d8292021-04-09 12:14:03 -04001478 this->writeWord(this->getType(type.componentType().toCompound(
1479 fContext, /*columns=*/type.rows(), /*rows=*/1)),
Ethan Nicholas84645e32017-02-09 13:57:14 -05001480 out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001481 SpvId columnId = this->nextId(&type);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001482 this->writeWord(columnId, out);
1483 columnIds.push_back(columnId);
John Stiles392d8292021-04-09 12:14:03 -04001484 for (int row = 0; row < type.rows(); row++) {
Ethan Nicholas84645e32017-02-09 13:57:14 -05001485 this->writeWord(row == column ? diagonal : zeroId, out);
1486 }
1487 }
1488 this->writeOpCode(SpvOpCompositeConstruct, 3 + type.columns(),
1489 out);
1490 this->writeWord(this->getType(type), out);
1491 this->writeWord(id, out);
John Stilesf621e232020-08-25 13:33:02 -04001492 for (SpvId columnId : columnIds) {
1493 this->writeWord(columnId, out);
Ethan Nicholas84645e32017-02-09 13:57:14 -05001494 }
1495}
1496
John Stiles268a73f2021-04-07 12:30:22 -04001497SpvId SPIRVCodeGenerator::writeMatrixCopy(SpvId src, const Type& srcType, const Type& dstType,
1498 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05001499 SkASSERT(srcType.isMatrix());
1500 SkASSERT(dstType.isMatrix());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001501 SkASSERT(srcType.componentType() == dstType.componentType());
John Stiles268a73f2021-04-07 12:30:22 -04001502 SpvId id = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001503 SpvId srcColumnType = this->getType(srcType.componentType().toCompound(fContext,
1504 srcType.rows(),
1505 1));
1506 SpvId dstColumnType = this->getType(dstType.componentType().toCompound(fContext,
1507 dstType.rows(),
1508 1));
John Stiles92671832021-04-06 09:24:55 -04001509 SkASSERT(dstType.componentType().isFloat());
Brian Osmancc914522021-09-24 18:58:37 +00001510 Literal zero(/*offset=*/-1, /*value=*/0.0, &dstType.componentType());
John Stiles7591d4b2021-09-13 13:32:06 -04001511 const SpvId zeroId = this->writeLiteral(zero);
Brian Osmancc914522021-09-24 18:58:37 +00001512 Literal one(/*offset=*/-1, /*value=*/1.0, &dstType.componentType());
John Stiles7591d4b2021-09-13 13:32:06 -04001513 const SpvId oneId = this->writeLiteral(one);
John Stiles92671832021-04-06 09:24:55 -04001514
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001515 SpvId columns[4];
1516 for (int i = 0; i < dstType.columns(); i++) {
1517 if (i < srcType.columns()) {
1518 // we're still inside the src matrix, copy the column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001519 SpvId srcColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001520 this->writeInstruction(SpvOpCompositeExtract, srcColumnType, srcColumn, src, i, out);
1521 SpvId dstColumn;
1522 if (srcType.rows() == dstType.rows()) {
1523 // columns are equal size, don't need to do anything
1524 dstColumn = srcColumn;
1525 }
1526 else if (dstType.rows() > srcType.rows()) {
1527 // dst column is bigger, need to zero-pad it
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001528 dstColumn = this->nextId(&dstType);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001529 int delta = dstType.rows() - srcType.rows();
1530 this->writeOpCode(SpvOpCompositeConstruct, 4 + delta, out);
1531 this->writeWord(dstColumnType, out);
1532 this->writeWord(dstColumn, out);
1533 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001534 for (int j = srcType.rows(); j < dstType.rows(); ++j) {
1535 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001536 }
1537 }
1538 else {
1539 // dst column is smaller, need to swizzle the src column
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001540 dstColumn = this->nextId(&dstType);
John Stiles92671832021-04-06 09:24:55 -04001541 this->writeOpCode(SpvOpVectorShuffle, 5 + dstType.rows(), out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001542 this->writeWord(dstColumnType, out);
1543 this->writeWord(dstColumn, out);
1544 this->writeWord(srcColumn, out);
1545 this->writeWord(srcColumn, out);
John Stiles92671832021-04-06 09:24:55 -04001546 for (int j = 0; j < dstType.rows(); j++) {
John Stilesf621e232020-08-25 13:33:02 -04001547 this->writeWord(j, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001548 }
1549 }
1550 columns[i] = dstColumn;
1551 } else {
John Stiles92671832021-04-06 09:24:55 -04001552 // we're past the end of the src matrix, need to synthesize an identity-matrix column
1553 SpvId identityColumn = this->nextId(&dstType);
1554 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.rows(), out);
1555 this->writeWord(dstColumnType, out);
1556 this->writeWord(identityColumn, out);
1557 for (int j = 0; j < dstType.rows(); ++j) {
1558 this->writeWord((i == j) ? oneId : zeroId, out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001559 }
John Stiles92671832021-04-06 09:24:55 -04001560 columns[i] = identityColumn;
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001561 }
1562 }
1563 this->writeOpCode(SpvOpCompositeConstruct, 3 + dstType.columns(), out);
1564 this->writeWord(this->getType(dstType), out);
1565 this->writeWord(id, out);
1566 for (int i = 0; i < dstType.columns(); i++) {
1567 this->writeWord(columns[i], out);
1568 }
John Stiles268a73f2021-04-07 12:30:22 -04001569 return id;
Ethan Nicholas84645e32017-02-09 13:57:14 -05001570}
1571
John Stilesbeb2fbf2021-07-08 18:54:39 -04001572void SPIRVCodeGenerator::addColumnEntry(const Type& columnType,
Ethan Nicholascc5d3e02019-04-19 09:50:56 -04001573 std::vector<SpvId>* currentColumn,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001574 std::vector<SpvId>* columnIds,
John Stilesbeb2fbf2021-07-08 18:54:39 -04001575 int rows,
1576 SpvId entry,
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001577 OutputStream& out) {
John Stilesbeb2fbf2021-07-08 18:54:39 -04001578 SkASSERT((int)currentColumn->size() < rows);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001579 currentColumn->push_back(entry);
John Stilesbeb2fbf2021-07-08 18:54:39 -04001580 if ((int)currentColumn->size() == rows) {
1581 // Synthesize this column into a vector.
1582 SpvId columnId = this->writeComposite(*currentColumn, columnType, out);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001583 columnIds->push_back(columnId);
Ethan Nicholas5c46b722019-03-22 14:32:37 -04001584 currentColumn->clear();
1585 }
1586}
1587
John Stiles8cad6372021-04-07 12:31:13 -04001588SpvId SPIRVCodeGenerator::writeMatrixConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001589 const Type& type = c.type();
John Stiles9aeed132020-11-24 17:36:06 -05001590 SkASSERT(type.isMatrix());
John Stiles2bec8ab2021-04-06 18:40:04 -04001591 SkASSERT(!c.arguments().empty());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001592 const Type& arg0Type = c.arguments()[0]->type();
ethannicholasb3058bd2016-07-01 08:22:01 -07001593 // go ahead and write the arguments so we don't try to write new instructions in the middle of
1594 // an instruction
1595 std::vector<SpvId> arguments;
John Stiles2bec8ab2021-04-06 18:40:04 -04001596 arguments.reserve(c.arguments().size());
1597 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1598 arguments.push_back(this->writeExpression(*arg, out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001599 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001600
John Stiles268a73f2021-04-07 12:30:22 -04001601 if (arguments.size() == 1 && arg0Type.isVector()) {
1602 // Special-case handling of float4 -> mat2x2.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001603 SkASSERT(type.rows() == 2 && type.columns() == 2);
1604 SkASSERT(arg0Type.columns() == 4);
1605 SpvId componentType = this->getType(type.componentType());
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001606 SpvId v[4];
1607 for (int i = 0; i < 4; ++i) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04001608 v[i] = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001609 this->writeInstruction(SpvOpCompositeExtract, componentType, v[i], arguments[0], i,
1610 out);
Ethan Nicholasdc0e1c32017-07-21 13:23:34 -04001611 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001612 const Type& vecType = type.componentType().toCompound(fContext, /*columns=*/2, /*rows=*/1);
1613 SpvId v0v1 = this->writeComposite({v[0], v[1]}, vecType, out);
1614 SpvId v2v3 = this->writeComposite({v[2], v[3]}, vecType, out);
1615 return this->writeComposite({v0v1, v2v3}, type, out);
1616 }
1617
1618 int rows = type.rows();
1619 const Type& columnType = type.componentType().toCompound(fContext,
1620 /*columns=*/rows, /*rows=*/1);
1621 // SpvIds of completed columns of the matrix.
1622 std::vector<SpvId> columnIds;
1623 // SpvIds of scalars we have written to the current column so far.
1624 std::vector<SpvId> currentColumn;
1625 for (size_t i = 0; i < arguments.size(); i++) {
1626 const Type& argType = c.arguments()[i]->type();
1627 if (currentColumn.empty() && argType.isVector() && argType.columns() == rows) {
1628 // This vector is a complete matrix column by itself and can be used as-is.
1629 columnIds.push_back(arguments[i]);
1630 } else if (argType.columns() == 1) {
1631 // This argument is a lone scalar and can be added to the current column as-is.
1632 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, arguments[i], out);
1633 } else {
1634 // This argument needs to be decomposed into its constituent scalars.
1635 SpvId componentType = this->getType(argType.componentType());
1636 for (int j = 0; j < argType.columns(); ++j) {
1637 SpvId swizzle = this->nextId(&argType);
1638 this->writeInstruction(SpvOpCompositeExtract, componentType, swizzle,
1639 arguments[i], j, out);
1640 this->addColumnEntry(columnType, &currentColumn, &columnIds, rows, swizzle, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001641 }
1642 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001643 }
John Stilesbeb2fbf2021-07-08 18:54:39 -04001644 SkASSERT(columnIds.size() == (size_t) type.columns());
1645 return this->writeComposite(columnIds, type, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001646}
1647
John Stiles8cad6372021-04-07 12:31:13 -04001648SpvId SPIRVCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1649 OutputStream& out) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001650 return c.type().isMatrix() ? this->writeMatrixConstructor(c, out)
1651 : this->writeVectorConstructor(c, out);
1652}
1653
John Stiles8cad6372021-04-07 12:31:13 -04001654SpvId SPIRVCodeGenerator::writeVectorConstructor(const ConstructorCompound& c, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001655 const Type& type = c.type();
John Stilesd986f472021-04-06 15:54:43 -04001656 const Type& componentType = type.componentType();
John Stiles9aeed132020-11-24 17:36:06 -05001657 SkASSERT(type.isVector());
John Stilesd986f472021-04-06 15:54:43 -04001658
1659 if (c.isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001660 return this->writeConstantVector(c);
1661 }
John Stilesd986f472021-04-06 15:54:43 -04001662
ethannicholasb3058bd2016-07-01 08:22:01 -07001663 std::vector<SpvId> arguments;
John Stiles6de2e1d2021-07-09 12:41:55 -04001664 arguments.reserve(c.arguments().size());
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001665 for (size_t i = 0; i < c.arguments().size(); i++) {
1666 const Type& argType = c.arguments()[i]->type();
John Stilesd986f472021-04-06 15:54:43 -04001667 SkASSERT(componentType == argType.componentType());
John Stiles48c28842021-01-14 11:05:03 -05001668
John Stiles6de2e1d2021-07-09 12:41:55 -04001669 SpvId arg = this->writeExpression(*c.arguments()[i], out);
1670 if (argType.isMatrix()) {
1671 // CompositeConstruct cannot take a 2x2 matrix as an input, so we need to extract out
1672 // each scalar separately.
1673 SkASSERT(argType.rows() == 2);
1674 SkASSERT(argType.columns() == 2);
1675 for (int j = 0; j < 4; ++j) {
1676 SpvId componentId = this->nextId(&componentType);
1677 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
1678 componentId, arg, j / 2, j % 2, out);
1679 arguments.push_back(componentId);
1680 }
1681 } else if (argType.isVector()) {
John Stilesd986f472021-04-06 15:54:43 -04001682 // There's a bug in the Intel Vulkan driver where OpCompositeConstruct doesn't handle
1683 // vector arguments at all, so we always extract each vector component and pass them
1684 // into OpCompositeConstruct individually.
Ethan Nicholas30d30222020-09-11 12:27:26 -04001685 for (int j = 0; j < argType.columns(); j++) {
John Stilesd986f472021-04-06 15:54:43 -04001686 SpvId componentId = this->nextId(&componentType);
1687 this->writeInstruction(SpvOpCompositeExtract, this->getType(componentType),
John Stiles6de2e1d2021-07-09 12:41:55 -04001688 componentId, arg, j, out);
John Stilesd986f472021-04-06 15:54:43 -04001689 arguments.push_back(componentId);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001690 }
Ethan Nicholas11e5bff2018-01-29 11:08:38 -05001691 } else {
John Stiles6de2e1d2021-07-09 12:41:55 -04001692 arguments.push_back(arg);
Ethan Nicholas26a8d902018-01-29 09:25:51 -05001693 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001694 }
John Stilesb14a8192021-04-05 11:40:46 -04001695
1696 return this->writeComposite(arguments, type, out);
1697}
1698
1699SpvId SPIRVCodeGenerator::writeComposite(const std::vector<SpvId>& arguments,
1700 const Type& type,
1701 OutputStream& out) {
John Stilesd47330f2021-04-08 23:25:52 -04001702 SkASSERT(arguments.size() == (type.isStruct() ? type.fields().size() : (size_t)type.columns()));
John Stiles2938eea2021-04-01 18:58:25 -04001703
Ethan Nicholas7f015882021-03-23 14:16:52 -04001704 SpvId result = this->nextId(&type);
John Stiles2938eea2021-04-01 18:58:25 -04001705 this->writeOpCode(SpvOpCompositeConstruct, 3 + (int32_t) arguments.size(), out);
1706 this->writeWord(this->getType(type), out);
1707 this->writeWord(result, out);
1708 for (SpvId id : arguments) {
1709 this->writeWord(id, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001710 }
1711 return result;
1712}
1713
John Stiles2938eea2021-04-01 18:58:25 -04001714SpvId SPIRVCodeGenerator::writeConstructorSplat(const ConstructorSplat& c, OutputStream& out) {
1715 // Use writeConstantVector to deduplicate constant splats.
1716 if (c.isCompileTimeConstant()) {
1717 return this->writeConstantVector(c);
1718 }
1719
1720 // Write the splat argument.
1721 SpvId argument = this->writeExpression(*c.argument(), out);
1722
1723 // Generate a OpCompositeConstruct which repeats the argument N times.
John Stilesb14a8192021-04-05 11:40:46 -04001724 std::vector<SpvId> arguments(/*count*/ c.type().columns(), /*value*/ argument);
1725 return this->writeComposite(arguments, c.type(), out);
John Stiles2938eea2021-04-01 18:58:25 -04001726}
1727
1728
John Stilesd47330f2021-04-08 23:25:52 -04001729SpvId SPIRVCodeGenerator::writeCompositeConstructor(const AnyConstructor& c, OutputStream& out) {
1730 SkASSERT(c.type().isArray() || c.type().isStruct());
1731 auto ctorArgs = c.argumentSpan();
1732
Ethan Nicholasbd553222017-07-18 15:54:59 -04001733 std::vector<SpvId> arguments;
John Stilesd47330f2021-04-08 23:25:52 -04001734 arguments.reserve(ctorArgs.size());
1735 for (const std::unique_ptr<Expression>& arg : ctorArgs) {
1736 arguments.push_back(this->writeExpression(*arg, out));
Ethan Nicholasbd553222017-07-18 15:54:59 -04001737 }
John Stilesd47330f2021-04-08 23:25:52 -04001738
1739 return this->writeComposite(arguments, c.type(), out);
Ethan Nicholasbd553222017-07-18 15:54:59 -04001740}
1741
John Stilesfd7252f2021-04-04 22:24:40 -04001742SpvId SPIRVCodeGenerator::writeConstructorScalarCast(const ConstructorScalarCast& c,
1743 OutputStream& out) {
1744 const Type& type = c.type();
1745 if (this->getActualType(type) == this->getActualType(c.argument()->type())) {
1746 return this->writeExpression(*c.argument(), out);
1747 }
John Stilesb14a8192021-04-05 11:40:46 -04001748
1749 const Expression& ctorExpr = *c.argument();
1750 SpvId expressionId = this->writeExpression(ctorExpr, out);
1751 return this->castScalarToType(expressionId, ctorExpr.type(), type, out);
1752}
1753
John Stiles8cad6372021-04-07 12:31:13 -04001754SpvId SPIRVCodeGenerator::writeConstructorCompoundCast(const ConstructorCompoundCast& c,
1755 OutputStream& out) {
John Stilesb14a8192021-04-05 11:40:46 -04001756 const Type& ctorType = c.type();
1757 const Type& argType = c.argument()->type();
John Stiles268a73f2021-04-07 12:30:22 -04001758 SkASSERT(ctorType.isVector() || ctorType.isMatrix());
John Stilesb14a8192021-04-05 11:40:46 -04001759
John Stiles268a73f2021-04-07 12:30:22 -04001760 // Write the composite that we are casting. If the actual type matches, we are done.
1761 SpvId compositeId = this->writeExpression(*c.argument(), out);
John Stilesb14a8192021-04-05 11:40:46 -04001762 if (this->getActualType(ctorType) == this->getActualType(argType)) {
John Stiles268a73f2021-04-07 12:30:22 -04001763 return compositeId;
1764 }
1765
1766 // writeMatrixCopy can cast matrices to a different type.
1767 if (ctorType.isMatrix()) {
1768 return this->writeMatrixCopy(compositeId, argType, ctorType, out);
John Stilesfd7252f2021-04-04 22:24:40 -04001769 }
John Stilesb14a8192021-04-05 11:40:46 -04001770
1771 // SPIR-V doesn't support vector(vector-of-different-type) directly, so we need to extract the
John Stilesd986f472021-04-06 15:54:43 -04001772 // components and convert each one manually.
John Stilesb14a8192021-04-05 11:40:46 -04001773 const Type& srcType = argType.componentType();
1774 const Type& dstType = ctorType.componentType();
1775
1776 std::vector<SpvId> arguments;
John Stiles268a73f2021-04-07 12:30:22 -04001777 arguments.reserve(argType.columns());
John Stilesb14a8192021-04-05 11:40:46 -04001778 for (int index = 0; index < argType.columns(); ++index) {
1779 SpvId componentId = this->nextId(&srcType);
1780 this->writeInstruction(SpvOpCompositeExtract, this->getType(srcType), componentId,
John Stiles268a73f2021-04-07 12:30:22 -04001781 compositeId, index, out);
John Stilesb14a8192021-04-05 11:40:46 -04001782 arguments.push_back(this->castScalarToType(componentId, srcType, dstType, out));
John Stilesfd7252f2021-04-04 22:24:40 -04001783 }
John Stilesb14a8192021-04-05 11:40:46 -04001784
1785 return this->writeComposite(arguments, ctorType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001786}
1787
John Stilese1182782021-03-30 22:09:37 -04001788SpvId SPIRVCodeGenerator::writeConstructorDiagonalMatrix(const ConstructorDiagonalMatrix& c,
1789 OutputStream& out) {
1790 const Type& type = c.type();
1791 SkASSERT(type.isMatrix());
1792 SkASSERT(c.argument()->type().isScalar());
1793
1794 // Write out the scalar argument.
1795 SpvId argument = this->writeExpression(*c.argument(), out);
1796
1797 // Build the diagonal matrix.
1798 SpvId result = this->nextId(&type);
1799 this->writeUniformScaleMatrix(result, argument, type, out);
1800 return result;
1801}
1802
John Stiles5abb9e12021-04-06 13:47:19 -04001803SpvId SPIRVCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1804 OutputStream& out) {
1805 // Write the input matrix.
1806 SpvId argument = this->writeExpression(*c.argument(), out);
1807
1808 // Use matrix-copy to resize the input matrix to its new size.
John Stiles268a73f2021-04-07 12:30:22 -04001809 return this->writeMatrixCopy(argument, c.argument()->type(), c.type(), out);
John Stiles5abb9e12021-04-06 13:47:19 -04001810}
1811
John Stiles9485b552021-01-27 11:47:00 -05001812static SpvStorageClass_ get_storage_class(const Variable& var,
1813 SpvStorageClass_ fallbackStorageClass) {
1814 const Modifiers& modifiers = var.modifiers();
ethannicholasb3058bd2016-07-01 08:22:01 -07001815 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001816 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001817 return SpvStorageClassInput;
John Stiles9485b552021-01-27 11:47:00 -05001818 }
1819 if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001820 SkASSERT(!(modifiers.fLayout.fFlags & Layout::kPushConstant_Flag));
ethannicholasb3058bd2016-07-01 08:22:01 -07001821 return SpvStorageClassOutput;
John Stiles9485b552021-01-27 11:47:00 -05001822 }
1823 if (modifiers.fFlags & Modifiers::kUniform_Flag) {
Ethan Nicholas39204fd2017-11-27 13:12:30 -05001824 if (modifiers.fLayout.fFlags & Layout::kPushConstant_Flag) {
ethannicholas8ac838d2016-11-22 08:39:36 -08001825 return SpvStorageClassPushConstant;
1826 }
John Stiles9485b552021-01-27 11:47:00 -05001827 if (var.type().typeKind() == Type::TypeKind::kSampler ||
1828 var.type().typeKind() == Type::TypeKind::kSeparateSampler ||
1829 var.type().typeKind() == Type::TypeKind::kTexture) {
1830 return SpvStorageClassUniformConstant;
1831 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001832 return SpvStorageClassUniform;
ethannicholasb3058bd2016-07-01 08:22:01 -07001833 }
John Stiles9485b552021-01-27 11:47:00 -05001834 return fallbackStorageClass;
ethannicholasb3058bd2016-07-01 08:22:01 -07001835}
1836
John Stiles9485b552021-01-27 11:47:00 -05001837static SpvStorageClass_ get_storage_class(const Expression& expr) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001838 switch (expr.kind()) {
1839 case Expression::Kind::kVariableReference: {
Ethan Nicholas78686922020-10-08 06:46:27 -04001840 const Variable& var = *expr.as<VariableReference>().variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001841 if (var.storage() != Variable::Storage::kGlobal) {
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001842 return SpvStorageClassFunction;
1843 }
John Stiles9485b552021-01-27 11:47:00 -05001844 return get_storage_class(var, SpvStorageClassPrivate);
Ethan Nicholasc6f5e102017-03-31 14:53:17 -04001845 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001846 case Expression::Kind::kFieldAccess:
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001847 return get_storage_class(*expr.as<FieldAccess>().base());
Ethan Nicholase6592142020-09-08 10:22:09 -04001848 case Expression::Kind::kIndex:
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001849 return get_storage_class(*expr.as<IndexExpression>().base());
ethannicholasb3058bd2016-07-01 08:22:01 -07001850 default:
1851 return SpvStorageClassFunction;
1852 }
1853}
1854
Ethan Nicholas0df1b042017-03-31 13:56:23 -04001855std::vector<SpvId> SPIRVCodeGenerator::getAccessChain(const Expression& expr, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001856 std::vector<SpvId> chain;
Ethan Nicholase6592142020-09-08 10:22:09 -04001857 switch (expr.kind()) {
1858 case Expression::Kind::kIndex: {
John Stiles0693fb82021-01-22 18:27:52 -05001859 const IndexExpression& indexExpr = expr.as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001860 chain = this->getAccessChain(*indexExpr.base(), out);
1861 chain.push_back(this->writeExpression(*indexExpr.index(), out));
ethannicholasb3058bd2016-07-01 08:22:01 -07001862 break;
1863 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001864 case Expression::Kind::kFieldAccess: {
John Stiles0693fb82021-01-22 18:27:52 -05001865 const FieldAccess& fieldExpr = expr.as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001866 chain = this->getAccessChain(*fieldExpr.base(), out);
Brian Osmancc914522021-09-24 18:58:37 +00001867 Literal index(/*offset=*/-1, fieldExpr.fieldIndex(), fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04001868 chain.push_back(this->writeLiteral(index));
ethannicholasb3058bd2016-07-01 08:22:01 -07001869 break;
1870 }
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001871 default: {
1872 SpvId id = this->getLValue(expr, out)->getPointer();
John Stiles3f14d282021-02-05 09:31:04 -05001873 SkASSERT(id != (SpvId) -1);
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001874 chain.push_back(id);
Ethan Nicholasb13f3692021-09-10 16:49:42 -04001875 break;
Ethan Nicholasa9a06902019-01-07 14:42:40 -05001876 }
ethannicholasb3058bd2016-07-01 08:22:01 -07001877 }
1878 return chain;
1879}
1880
1881class PointerLValue : public SPIRVCodeGenerator::LValue {
1882public:
Ethan Nicholase0707b72021-03-17 11:16:41 -04001883 PointerLValue(SPIRVCodeGenerator& gen, SpvId pointer, bool isMemoryObject, SpvId type,
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001884 SPIRVCodeGenerator::Precision precision)
ethannicholasb3058bd2016-07-01 08:22:01 -07001885 : fGen(gen)
1886 , fPointer(pointer)
Ethan Nicholase0707b72021-03-17 11:16:41 -04001887 , fIsMemoryObject(isMemoryObject)
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001888 , fType(type)
1889 , fPrecision(precision) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001890
John Stiles1cf2c8d2020-08-13 22:58:04 -04001891 SpvId getPointer() override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001892 return fPointer;
1893 }
1894
Ethan Nicholase0707b72021-03-17 11:16:41 -04001895 bool isMemoryObjectPointer() const override {
1896 return fIsMemoryObject;
1897 }
1898
John Stiles1cf2c8d2020-08-13 22:58:04 -04001899 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001900 SpvId result = fGen.nextId(fPrecision);
ethannicholasb3058bd2016-07-01 08:22:01 -07001901 fGen.writeInstruction(SpvOpLoad, fType, result, fPointer, out);
1902 return result;
1903 }
1904
John Stiles1cf2c8d2020-08-13 22:58:04 -04001905 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001906 fGen.writeInstruction(SpvOpStore, fPointer, value, out);
1907 }
1908
1909private:
1910 SPIRVCodeGenerator& fGen;
1911 const SpvId fPointer;
Ethan Nicholase0707b72021-03-17 11:16:41 -04001912 const bool fIsMemoryObject;
ethannicholasb3058bd2016-07-01 08:22:01 -07001913 const SpvId fType;
Ethan Nicholas10e93b62019-03-20 10:46:14 -04001914 const SPIRVCodeGenerator::Precision fPrecision;
ethannicholasb3058bd2016-07-01 08:22:01 -07001915};
1916
1917class SwizzleLValue : public SPIRVCodeGenerator::LValue {
1918public:
John Stiles750109b2020-10-30 13:45:46 -04001919 SwizzleLValue(SPIRVCodeGenerator& gen, SpvId vecPointer, const ComponentArray& components,
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001920 const Type& baseType, const Type& swizzleType)
ethannicholasb3058bd2016-07-01 08:22:01 -07001921 : fGen(gen)
1922 , fVecPointer(vecPointer)
1923 , fComponents(components)
John Stiles3f14d282021-02-05 09:31:04 -05001924 , fBaseType(&baseType)
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001925 , fSwizzleType(&swizzleType) {}
ethannicholasb3058bd2016-07-01 08:22:01 -07001926
John Stiles3f14d282021-02-05 09:31:04 -05001927 bool applySwizzle(const ComponentArray& components, const Type& newType) override {
1928 ComponentArray updatedSwizzle;
1929 for (int8_t component : components) {
1930 if (component < 0 || component >= fComponents.count()) {
1931 SkDEBUGFAILF("swizzle accessed nonexistent component %d", (int)component);
1932 return false;
1933 }
1934 updatedSwizzle.push_back(fComponents[component]);
1935 }
1936 fComponents = updatedSwizzle;
1937 fSwizzleType = &newType;
1938 return true;
ethannicholasb3058bd2016-07-01 08:22:01 -07001939 }
1940
John Stiles1cf2c8d2020-08-13 22:58:04 -04001941 SpvId load(OutputStream& out) override {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001942 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001943 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001944 SpvId result = fGen.nextId(fBaseType);
ethannicholasb3058bd2016-07-01 08:22:01 -07001945 fGen.writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) fComponents.size(), out);
John Stiles3f14d282021-02-05 09:31:04 -05001946 fGen.writeWord(fGen.getType(*fSwizzleType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001947 fGen.writeWord(result, out);
1948 fGen.writeWord(base, out);
1949 fGen.writeWord(base, out);
1950 for (int component : fComponents) {
1951 fGen.writeWord(component, out);
1952 }
1953 return result;
1954 }
1955
John Stiles1cf2c8d2020-08-13 22:58:04 -04001956 void store(SpvId value, OutputStream& out) override {
ethannicholasb3058bd2016-07-01 08:22:01 -07001957 // use OpVectorShuffle to mix and match the vector components. We effectively create
1958 // a virtual vector out of the concatenation of the left and right vectors, and then
Greg Daniel64773e62016-11-22 09:44:03 -05001959 // select components from this virtual vector to make the result vector. For
ethannicholasb3058bd2016-07-01 08:22:01 -07001960 // instance, given:
Ethan Nicholas5af9ea32017-07-28 15:19:46 -04001961 // float3L = ...;
1962 // float3R = ...;
ethannicholasb3058bd2016-07-01 08:22:01 -07001963 // L.xz = R.xy;
Greg Daniel64773e62016-11-22 09:44:03 -05001964 // 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 -07001965 // our result vector to look like (R.x, L.y, R.y), so we need to select indices
1966 // (3, 1, 4).
Ethan Nicholas7f015882021-03-23 14:16:52 -04001967 SpvId base = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001968 fGen.writeInstruction(SpvOpLoad, fGen.getType(*fBaseType), base, fVecPointer, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04001969 SpvId shuffle = fGen.nextId(fBaseType);
John Stiles3f14d282021-02-05 09:31:04 -05001970 fGen.writeOpCode(SpvOpVectorShuffle, 5 + fBaseType->columns(), out);
1971 fGen.writeWord(fGen.getType(*fBaseType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07001972 fGen.writeWord(shuffle, out);
1973 fGen.writeWord(base, out);
1974 fGen.writeWord(value, out);
John Stiles3f14d282021-02-05 09:31:04 -05001975 for (int i = 0; i < fBaseType->columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07001976 // current offset into the virtual vector, defaults to pulling the unmodified
1977 // value from the left side
1978 int offset = i;
1979 // check to see if we are writing this component
1980 for (size_t j = 0; j < fComponents.size(); j++) {
1981 if (fComponents[j] == i) {
Greg Daniel64773e62016-11-22 09:44:03 -05001982 // we're writing to this component, so adjust the offset to pull from
ethannicholasb3058bd2016-07-01 08:22:01 -07001983 // the correct component of the right side instead of preserving the
1984 // value from the left
John Stiles3f14d282021-02-05 09:31:04 -05001985 offset = (int) (j + fBaseType->columns());
ethannicholasb3058bd2016-07-01 08:22:01 -07001986 break;
1987 }
1988 }
1989 fGen.writeWord(offset, out);
1990 }
1991 fGen.writeInstruction(SpvOpStore, fVecPointer, shuffle, out);
1992 }
1993
1994private:
1995 SPIRVCodeGenerator& fGen;
1996 const SpvId fVecPointer;
John Stiles3f14d282021-02-05 09:31:04 -05001997 ComponentArray fComponents;
1998 const Type* fBaseType;
1999 const Type* fSwizzleType;
ethannicholasb3058bd2016-07-01 08:22:01 -07002000};
2001
John Stilese40d1662021-01-29 10:08:50 -05002002int SPIRVCodeGenerator::findUniformFieldIndex(const Variable& var) const {
2003 auto iter = fTopLevelUniformMap.find(&var);
2004 return (iter != fTopLevelUniformMap.end()) ? iter->second : -1;
2005}
2006
Greg Daniel64773e62016-11-22 09:44:03 -05002007std::unique_ptr<SPIRVCodeGenerator::LValue> SPIRVCodeGenerator::getLValue(const Expression& expr,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002008 OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002009 const Type& type = expr.type();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002010 Precision precision = type.highPrecision() ? Precision::kDefault : Precision::kRelaxed;
Ethan Nicholase6592142020-09-08 10:22:09 -04002011 switch (expr.kind()) {
2012 case Expression::Kind::kVariableReference: {
John Stiles0de76f72021-01-29 09:19:39 -05002013 const Variable& var = *expr.as<VariableReference>().variable();
John Stilese40d1662021-01-29 10:08:50 -05002014 int uniformIdx = this->findUniformFieldIndex(var);
2015 if (uniformIdx >= 0) {
Brian Osmancc914522021-09-24 18:58:37 +00002016 Literal uniformIdxLiteral{/*offset=*/-1, (double)uniformIdx,
John Stiles7591d4b2021-09-13 13:32:06 -04002017 fContext.fTypes.fInt.get()};
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002018 SpvId memberId = this->nextId(nullptr);
John Stilese40d1662021-01-29 10:08:50 -05002019 SpvId typeId = this->getPointerType(type, SpvStorageClassUniform);
John Stiles7591d4b2021-09-13 13:32:06 -04002020 SpvId uniformIdxId = this->writeLiteral(uniformIdxLiteral);
John Stilese40d1662021-01-29 10:08:50 -05002021 this->writeInstruction(SpvOpAccessChain, typeId, memberId, fUniformBufferId,
2022 uniformIdxId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002023 return std::make_unique<PointerLValue>(*this, memberId,
2024 /*isMemoryObjectPointer=*/true,
2025 this->getType(type), precision);
John Stilese40d1662021-01-29 10:08:50 -05002026 }
Brian Osman99ddd2a2021-08-27 11:21:12 -04002027 SpvId typeId = this->getType(type, this->memoryLayoutForVariable(var));
ethannicholasd598f792016-07-25 10:08:54 -07002028 auto entry = fVariableMap.find(&var);
John Stiles9078a892021-08-18 15:03:17 -04002029 SkASSERTF(entry != fVariableMap.end(), "%s", expr.description().c_str());
Ethan Nicholase0707b72021-03-17 11:16:41 -04002030 return std::make_unique<PointerLValue>(*this, entry->second,
2031 /*isMemoryObjectPointer=*/true,
2032 typeId, precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002033 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002034 case Expression::Kind::kIndex: // fall through
2035 case Expression::Kind::kFieldAccess: {
ethannicholasb3058bd2016-07-01 08:22:01 -07002036 std::vector<SpvId> chain = this->getAccessChain(expr, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002037 SpvId member = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002038 this->writeOpCode(SpvOpAccessChain, (SpvId) (3 + chain.size()), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002039 this->writeWord(this->getPointerType(type, get_storage_class(expr)), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002040 this->writeWord(member, out);
2041 for (SpvId idx : chain) {
2042 this->writeWord(idx, out);
2043 }
Ethan Nicholase0707b72021-03-17 11:16:41 -04002044 return std::make_unique<PointerLValue>(*this, member, /*isMemoryObjectPointer=*/false,
2045 this->getType(type), precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002046 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002047 case Expression::Kind::kSwizzle: {
John Stiles0693fb82021-01-22 18:27:52 -05002048 const Swizzle& swizzle = expr.as<Swizzle>();
John Stiles3f14d282021-02-05 09:31:04 -05002049 std::unique_ptr<LValue> lvalue = this->getLValue(*swizzle.base(), out);
2050 if (lvalue->applySwizzle(swizzle.components(), type)) {
2051 return lvalue;
2052 }
2053 SpvId base = lvalue->getPointer();
2054 if (base == (SpvId) -1) {
Brian Osmancc914522021-09-24 18:58:37 +00002055 fContext.fErrors->error(swizzle.fOffset, "unable to retrieve lvalue from swizzle");
John Stiles5570c512020-11-19 17:58:07 -05002056 }
John Stiles3f14d282021-02-05 09:31:04 -05002057 if (swizzle.components().size() == 1) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002058 SpvId member = this->nextId(nullptr);
John Stilesb5db4822021-01-21 13:04:40 -05002059 SpvId typeId = this->getPointerType(type, get_storage_class(*swizzle.base()));
Brian Osmancc914522021-09-24 18:58:37 +00002060 Literal index(/*offset=*/-1, swizzle.components()[0], fContext.fTypes.fInt.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002061 SpvId indexId = this->writeLiteral(index);
John Stilesb5db4822021-01-21 13:04:40 -05002062 this->writeInstruction(SpvOpAccessChain, typeId, member, base, indexId, out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002063 return std::make_unique<PointerLValue>(*this,
2064 member,
2065 /*isMemoryObjectPointer=*/false,
2066 this->getType(type),
John Stiles5570c512020-11-19 17:58:07 -05002067 precision);
ethannicholasb3058bd2016-07-01 08:22:01 -07002068 } else {
John Stiles5570c512020-11-19 17:58:07 -05002069 return std::make_unique<SwizzleLValue>(*this, base, swizzle.components(),
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002070 swizzle.base()->type(), type);
ethannicholasb3058bd2016-07-01 08:22:01 -07002071 }
2072 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04002073 default: {
Kevin Lubickbe03ef12021-06-16 15:28:00 -04002074 // expr isn't actually an lvalue, create a placeholder variable for it. This case
2075 // happens due to the need to store values in temporary variables during function
2076 // calls (see comments in getFunctionType); erroneous uses of rvalues as lvalues
2077 // should have been caught by IRGenerator
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002078 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002079 SpvId pointerType = this->getPointerType(type, SpvStorageClassFunction);
2080 this->writeInstruction(SpvOpVariable, pointerType, result, SpvStorageClassFunction,
ethannicholasd598f792016-07-25 10:08:54 -07002081 fVariableBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002082 this->writeInstruction(SpvOpStore, result, this->writeExpression(expr, out), out);
Ethan Nicholase0707b72021-03-17 11:16:41 -04002083 return std::make_unique<PointerLValue>(*this, result, /*isMemoryObjectPointer=*/true,
2084 this->getType(type), precision);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002085 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002086 }
2087}
2088
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002089SpvId SPIRVCodeGenerator::writeVariableReference(const VariableReference& ref, OutputStream& out) {
John Stiles9078a892021-08-18 15:03:17 -04002090 const Variable* variable = ref.variable();
2091 if (variable->modifiers().fLayout.fBuiltin == DEVICE_FRAGCOORDS_BUILTIN) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002092 // Down below, we rewrite raw references to sk_FragCoord with expressions that reference
2093 // DEVICE_FRAGCOORDS_BUILTIN. This is a fake variable that means we need to directly access
2094 // the fragcoord; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002095 dsl::DSLGlobalVar fragCoord("sk_FragCoord");
Brian Salomond8d85b92021-07-07 09:41:17 -04002096 return this->getLValue(*dsl::DSLExpression(fragCoord).release(), out)->load(out);
2097 }
John Stiles9078a892021-08-18 15:03:17 -04002098 if (variable->modifiers().fLayout.fBuiltin == DEVICE_CLOCKWISE_BUILTIN) {
Brian Salomond8d85b92021-07-07 09:41:17 -04002099 // Down below, we rewrite raw references to sk_Clockwise with expressions that reference
2100 // DEVICE_CLOCKWISE_BUILTIN. This is a fake variable that means we need to directly
2101 // access front facing; do so now.
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002102 dsl::DSLGlobalVar clockwise("sk_Clockwise");
Brian Salomond8d85b92021-07-07 09:41:17 -04002103 return this->getLValue(*dsl::DSLExpression(clockwise).release(), out)->load(out);
2104 }
John Stilese40d1662021-01-29 10:08:50 -05002105
Brian Salomond8d85b92021-07-07 09:41:17 -04002106 // Handle inserting use of uniform to flip y when referencing sk_FragCoord.
Brian Salomond8d85b92021-07-07 09:41:17 -04002107 if (variable->modifiers().fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Brian Osmancc914522021-09-24 18:58:37 +00002108 this->addRTFlipUniform(ref.fOffset);
Brian Salomond8d85b92021-07-07 09:41:17 -04002109 // Use sk_RTAdjust to compute the flipped coordinate
2110 using namespace dsl;
2111 const char* DEVICE_COORDS_NAME = "__device_FragCoords";
2112 SymbolTable& symbols = *dsl::DSLWriter::SymbolTable();
2113 // Use a uniform to flip the Y coordinate. The new expression will be written in
2114 // terms of __device_FragCoords, which is a fake variable that means "access the
2115 // underlying fragcoords directly without flipping it".
Brian Osmancc914522021-09-24 18:58:37 +00002116 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04002117 SKSL_RTFLIP_NAME));
2118 if (!symbols[DEVICE_COORDS_NAME]) {
John Stiles0cac5ed2021-08-06 11:40:39 -04002119 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Salomond8d85b92021-07-07 09:41:17 -04002120 Modifiers modifiers;
2121 modifiers.fLayout.fBuiltin = DEVICE_FRAGCOORDS_BUILTIN;
Brian Osmancc914522021-09-24 18:58:37 +00002122 auto coordsVar = std::make_unique<Variable>(/*offset=*/-1,
John Stilesd7437ee2021-08-02 11:56:16 -04002123 fContext.fModifiersPool->add(modifiers),
2124 DEVICE_COORDS_NAME,
2125 fContext.fTypes.fFloat4.get(),
2126 true,
2127 Variable::Storage::kGlobal);
2128 fSPIRVBonusVariables.insert(coordsVar.get());
2129 symbols.add(std::move(coordsVar));
Greg Daniela85e4bf2020-06-17 16:32:45 -04002130 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002131 DSLGlobalVar deviceCoord(DEVICE_COORDS_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002132 std::unique_ptr<Expression> rtFlipSkSLExpr = rtFlip.release();
2133 DSLExpression x = DSLExpression(rtFlipSkSLExpr->clone()).x();
2134 DSLExpression y = DSLExpression(std::move(rtFlipSkSLExpr)).y();
2135 return this->writeExpression(*dsl::Float4(deviceCoord.x(),
2136 std::move(x) + std::move(y) * deviceCoord.y(),
2137 deviceCoord.z(),
2138 deviceCoord.w()).release(),
2139 out);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05002140 }
John Stiles1e1fe122021-01-29 12:18:46 -05002141
Brian Salomond8d85b92021-07-07 09:41:17 -04002142 // Handle flipping sk_Clockwise.
2143 if (variable->modifiers().fLayout.fBuiltin == SK_CLOCKWISE_BUILTIN) {
Brian Osmancc914522021-09-24 18:58:37 +00002144 this->addRTFlipUniform(ref.fOffset);
Brian Salomond8d85b92021-07-07 09:41:17 -04002145 using namespace dsl;
2146 const char* DEVICE_CLOCKWISE_NAME = "__device_Clockwise";
2147 SymbolTable& symbols = *dsl::DSLWriter::SymbolTable();
2148 // Use a uniform to flip the Y coordinate. The new expression will be written in
2149 // terms of __device_Clockwise, which is a fake variable that means "access the
2150 // underlying FrontFacing directly".
Brian Osmancc914522021-09-24 18:58:37 +00002151 DSLExpression rtFlip(DSLWriter::IRGenerator().convertIdentifier(/*offset=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04002152 SKSL_RTFLIP_NAME));
2153 if (!symbols[DEVICE_CLOCKWISE_NAME]) {
John Stiles0cac5ed2021-08-06 11:40:39 -04002154 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Salomond8d85b92021-07-07 09:41:17 -04002155 Modifiers modifiers;
2156 modifiers.fLayout.fBuiltin = DEVICE_CLOCKWISE_BUILTIN;
Brian Osmancc914522021-09-24 18:58:37 +00002157 auto clockwiseVar = std::make_unique<Variable>(/*offset=*/-1,
John Stilesd7437ee2021-08-02 11:56:16 -04002158 fContext.fModifiersPool->add(modifiers),
2159 DEVICE_CLOCKWISE_NAME,
2160 fContext.fTypes.fBool.get(),
2161 true,
2162 Variable::Storage::kGlobal);
2163 fSPIRVBonusVariables.insert(clockwiseVar.get());
2164 symbols.add(std::move(clockwiseVar));
Brian Salomond8d85b92021-07-07 09:41:17 -04002165 }
Ethan Nicholasa2d22b22021-07-15 10:35:54 -04002166 DSLGlobalVar deviceClockwise(DEVICE_CLOCKWISE_NAME);
Brian Salomond8d85b92021-07-07 09:41:17 -04002167 // FrontFacing in Vulkan is defined in terms of a top-down render target. In skia,
2168 // we use the default convention of "counter-clockwise face is front".
2169 return this->writeExpression(*dsl::Bool(Select(rtFlip.y() > 0,
2170 !deviceClockwise,
2171 deviceClockwise)).release(),
2172 out);
Chris Daltonb91c4662018-08-01 10:46:22 -06002173 }
John Stiles1e1fe122021-01-29 12:18:46 -05002174
Brian Salomond8d85b92021-07-07 09:41:17 -04002175 return this->getLValue(ref, out)->load(out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002176}
2177
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002178SpvId SPIRVCodeGenerator::writeIndexExpression(const IndexExpression& expr, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002179 if (expr.base()->type().isVector()) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002180 SpvId base = this->writeExpression(*expr.base(), out);
2181 SpvId index = this->writeExpression(*expr.index(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002182 SpvId result = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002183 this->writeInstruction(SpvOpVectorExtractDynamic, this->getType(expr.type()), result, base,
Ethan Nicholasa9a06902019-01-07 14:42:40 -05002184 index, out);
2185 return result;
2186 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002187 return getLValue(expr, out)->load(out);
2188}
2189
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002190SpvId SPIRVCodeGenerator::writeFieldAccess(const FieldAccess& f, OutputStream& out) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002191 return getLValue(f, out)->load(out);
2192}
2193
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002194SpvId SPIRVCodeGenerator::writeSwizzle(const Swizzle& swizzle, OutputStream& out) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002195 SpvId base = this->writeExpression(*swizzle.base(), out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002196 SpvId result = this->nextId(&swizzle.type());
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002197 size_t count = swizzle.components().size();
ethannicholasb3058bd2016-07-01 08:22:01 -07002198 if (count == 1) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002199 this->writeInstruction(SpvOpCompositeExtract, this->getType(swizzle.type()), result, base,
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002200 swizzle.components()[0], out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002201 } else {
2202 this->writeOpCode(SpvOpVectorShuffle, 5 + (int32_t) count, out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002203 this->writeWord(this->getType(swizzle.type()), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002204 this->writeWord(result, out);
2205 this->writeWord(base, out);
Brian Osman25647672020-09-15 15:16:56 -04002206 this->writeWord(base, out);
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002207 for (int component : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04002208 this->writeWord(component, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002209 }
2210 }
2211 return result;
2212}
2213
Greg Daniel64773e62016-11-22 09:44:03 -05002214SpvId SPIRVCodeGenerator::writeBinaryOperation(const Type& resultType,
2215 const Type& operandType, SpvId lhs,
2216 SpvId rhs, SpvOp_ ifFloat, SpvOp_ ifInt,
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002217 SpvOp_ ifUInt, SpvOp_ ifBool, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002218 SpvId result = this->nextId(&resultType);
ethannicholasd598f792016-07-25 10:08:54 -07002219 if (is_float(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002220 this->writeInstruction(ifFloat, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002221 } else if (is_signed(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002222 this->writeInstruction(ifInt, this->getType(resultType), result, lhs, rhs, out);
ethannicholasd598f792016-07-25 10:08:54 -07002223 } else if (is_unsigned(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002224 this->writeInstruction(ifUInt, this->getType(resultType), result, lhs, rhs, out);
John Stiles123501f2020-12-09 10:08:13 -05002225 } else if (is_bool(fContext, operandType)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002226 this->writeInstruction(ifBool, this->getType(resultType), result, lhs, rhs, out);
2227 } else {
Brian Osmancc914522021-09-24 18:58:37 +00002228 fContext.fErrors->error(operandType.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002229 "unsupported operand for binary expression: " + operandType.description());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002230 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002231 return result;
2232}
2233
Ethan Nicholas48e24052018-03-14 13:51:39 -04002234SpvId SPIRVCodeGenerator::foldToBool(SpvId id, const Type& operandType, SpvOp op,
2235 OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002236 if (operandType.isVector()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002237 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002238 this->writeInstruction(op, this->getType(*fContext.fTypes.fBool), result, id, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002239 return result;
2240 }
2241 return id;
2242}
2243
Ethan Nicholas68990be2017-07-13 09:36:52 -04002244SpvId SPIRVCodeGenerator::writeMatrixComparison(const Type& operandType, SpvId lhs, SpvId rhs,
2245 SpvOp_ floatOperator, SpvOp_ intOperator,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002246 SpvOp_ vectorMergeOperator, SpvOp_ mergeOperator,
Ethan Nicholas68990be2017-07-13 09:36:52 -04002247 OutputStream& out) {
2248 SpvOp_ compareOp = is_float(fContext, operandType) ? floatOperator : intOperator;
John Stiles9aeed132020-11-24 17:36:06 -05002249 SkASSERT(operandType.isMatrix());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002250 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2251 operandType.rows(),
2252 1));
John Stiles54e7c052021-01-11 14:22:36 -05002253 SpvId bvecType = this->getType(fContext.fTypes.fBool->toCompound(fContext,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002254 operandType.rows(),
Ethan Nicholas68990be2017-07-13 09:36:52 -04002255 1));
John Stiles54e7c052021-01-11 14:22:36 -05002256 SpvId boolType = this->getType(*fContext.fTypes.fBool);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002257 SpvId result = 0;
Ethan Nicholas0df21132018-07-10 09:37:51 -04002258 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002259 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002260 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002261 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002262 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002263 SpvId compare = this->nextId(&operandType);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002264 this->writeInstruction(compareOp, bvecType, compare, columnL, columnR, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002265 SpvId merge = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002266 this->writeInstruction(vectorMergeOperator, boolType, merge, compare, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002267 if (result != 0) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002268 SpvId next = this->nextId(nullptr);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002269 this->writeInstruction(mergeOperator, boolType, next, result, merge, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002270 result = next;
2271 }
2272 else {
Ethan Nicholas0df21132018-07-10 09:37:51 -04002273 result = merge;
Ethan Nicholas68990be2017-07-13 09:36:52 -04002274 }
2275 }
2276 return result;
2277}
2278
Ethan Nicholas0df21132018-07-10 09:37:51 -04002279SpvId SPIRVCodeGenerator::writeComponentwiseMatrixBinary(const Type& operandType, SpvId lhs,
John Stiles43b593c2021-05-13 22:03:27 -04002280 SpvId rhs, SpvOp_ op, OutputStream& out) {
John Stiles9aeed132020-11-24 17:36:06 -05002281 SkASSERT(operandType.isMatrix());
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002282 SpvId columnType = this->getType(operandType.componentType().toCompound(fContext,
2283 operandType.rows(),
2284 1));
John Stiles43b593c2021-05-13 22:03:27 -04002285 std::vector<SpvId> columns;
2286 columns.reserve(operandType.columns());
Ethan Nicholas0df21132018-07-10 09:37:51 -04002287 for (int i = 0; i < operandType.columns(); i++) {
Ethan Nicholas7f015882021-03-23 14:16:52 -04002288 SpvId columnL = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002289 this->writeInstruction(SpvOpCompositeExtract, columnType, columnL, lhs, i, out);
Ethan Nicholas7f015882021-03-23 14:16:52 -04002290 SpvId columnR = this->nextId(&operandType);
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002291 this->writeInstruction(SpvOpCompositeExtract, columnType, columnR, rhs, i, out);
John Stiles43b593c2021-05-13 22:03:27 -04002292 columns.push_back(this->nextId(&operandType));
Ethan Nicholas2f4652f2021-03-12 18:48:48 +00002293 this->writeInstruction(op, columnType, columns[i], columnL, columnR, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002294 }
John Stiles43b593c2021-05-13 22:03:27 -04002295 return this->writeComposite(columns, operandType, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002296}
2297
John Stiles9485b552021-01-27 11:47:00 -05002298static std::unique_ptr<Expression> create_literal_1(const Context& context, const Type& type) {
John Stiles7591d4b2021-09-13 13:32:06 -04002299 SkASSERT(type.isInteger() || type.isFloat());
Brian Osmancc914522021-09-24 18:58:37 +00002300 return Literal::Make(/*offset=*/-1, /*value=*/1.0, &type);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002301}
2302
John Stilesd94bfdd2021-03-25 11:44:08 -04002303SpvId SPIRVCodeGenerator::writeReciprocal(const Type& type, SpvId value, OutputStream& out) {
2304 SkASSERT(type.isFloat());
Brian Osmancc914522021-09-24 18:58:37 +00002305 SpvId one = this->writeLiteral({/*offset=*/-1, /*value=*/1, &type});
John Stilesd94bfdd2021-03-25 11:44:08 -04002306 SpvId reciprocal = this->nextId(&type);
2307 this->writeInstruction(SpvOpFDiv, this->getType(type), reciprocal, one, value, out);
2308 return reciprocal;
2309}
2310
John Stilesa91bf052021-05-17 09:34:03 -04002311SpvId SPIRVCodeGenerator::writeScalarToMatrixSplat(const Type& matrixType,
2312 SpvId scalarId,
2313 OutputStream& out) {
2314 // Splat the scalar into a vector.
2315 const Type& vectorType = matrixType.componentType().toCompound(fContext,
2316 /*columns=*/matrixType.rows(),
2317 /*rows=*/1);
2318 std::vector<SpvId> vecArguments(/*count*/ matrixType.rows(), /*value*/ scalarId);
2319 SpvId vectorId = this->writeComposite(vecArguments, vectorType, out);
2320
2321 // Splat the vector into a matrix.
2322 std::vector<SpvId> matArguments(/*count*/ matrixType.columns(), /*value*/ vectorId);
2323 return this->writeComposite(matArguments, matrixType, out);
2324}
2325
John Stiles45990502021-02-16 10:55:27 -05002326SpvId SPIRVCodeGenerator::writeBinaryExpression(const Type& leftType, SpvId lhs, Operator op,
Ethan Nicholas49465b42019-04-17 12:22:21 -04002327 const Type& rightType, SpvId rhs,
2328 const Type& resultType, OutputStream& out) {
John Stilesd0614f22020-12-09 11:11:41 -05002329 // The comma operator ignores the type of the left-hand side entirely.
John Stiles45990502021-02-16 10:55:27 -05002330 if (op.kind() == Token::Kind::TK_COMMA) {
John Stilesd0614f22020-12-09 11:11:41 -05002331 return rhs;
2332 }
Ethan Nicholas48e24052018-03-14 13:51:39 -04002333 // overall type we are operating on: float2, int, uint4...
ethannicholasb3058bd2016-07-01 08:22:01 -07002334 const Type* operandType;
Ethan Nicholas48e24052018-03-14 13:51:39 -04002335 // IR allows mismatched types in expressions (e.g. float2 * float), but they need special
2336 // handling in SPIR-V
Ethan Nicholas49465b42019-04-17 12:22:21 -04002337 if (this->getActualType(leftType) != this->getActualType(rightType)) {
John Stiles9aeed132020-11-24 17:36:06 -05002338 if (leftType.isVector() && rightType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002339 if (resultType.componentType().isFloat()) {
2340 switch (op.kind()) {
2341 case Token::Kind::TK_SLASH: {
2342 rhs = this->writeReciprocal(rightType, rhs, out);
2343 [[fallthrough]];
2344 }
2345 case Token::Kind::TK_STAR: {
2346 SpvId result = this->nextId(&resultType);
2347 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2348 result, lhs, rhs, out);
2349 return result;
2350 }
2351 default:
2352 break;
2353 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002354 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002355 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002356 const Type& vecType = leftType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002357 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002358 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2359 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002360 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002361 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002362 this->writeWord(rhs, out);
2363 }
2364 rhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002365 operandType = &leftType;
John Stiles9aeed132020-11-24 17:36:06 -05002366 } else if (rightType.isVector() && leftType.isNumber()) {
John Stilesd94bfdd2021-03-25 11:44:08 -04002367 if (resultType.componentType().isFloat()) {
2368 if (op.kind() == Token::Kind::TK_STAR) {
2369 SpvId result = this->nextId(&resultType);
2370 this->writeInstruction(SpvOpVectorTimesScalar, this->getType(resultType),
2371 result, rhs, lhs, out);
2372 return result;
2373 }
Ethan Nicholas49465b42019-04-17 12:22:21 -04002374 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002375 // promote number to vector
Ethan Nicholas49465b42019-04-17 12:22:21 -04002376 const Type& vecType = rightType;
Ethan Nicholas7f015882021-03-23 14:16:52 -04002377 SpvId vec = this->nextId(&vecType);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002378 this->writeOpCode(SpvOpCompositeConstruct, 3 + vecType.columns(), out);
2379 this->writeWord(this->getType(vecType), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002380 this->writeWord(vec, out);
Ethan Nicholas48e24052018-03-14 13:51:39 -04002381 for (int i = 0; i < vecType.columns(); i++) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002382 this->writeWord(lhs, out);
2383 }
2384 lhs = vec;
Ethan Nicholas49465b42019-04-17 12:22:21 -04002385 operandType = &rightType;
John Stiles9aeed132020-11-24 17:36:06 -05002386 } else if (leftType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002387 if (op.kind() == Token::Kind::TK_STAR) {
2388 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2389 SpvOp_ spvop;
2390 if (rightType.isMatrix()) {
2391 spvop = SpvOpMatrixTimesMatrix;
2392 } else if (rightType.isVector()) {
2393 spvop = SpvOpMatrixTimesVector;
2394 } else {
2395 SkASSERT(rightType.isScalar());
2396 spvop = SpvOpMatrixTimesScalar;
2397 }
2398 SpvId result = this->nextId(&resultType);
2399 this->writeInstruction(spvop, this->getType(resultType), result, lhs, rhs, out);
2400 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002401 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002402 // Matrix-op-vector is not supported in GLSL/SkSL for non-multiplication ops; we
2403 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002404 SkASSERT(rightType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002405
2406 // Splat rhs across an entire matrix so we can reuse the matrix-op-matrix path.
2407 SpvId rhsMatrix = this->writeScalarToMatrixSplat(leftType, rhs, out);
2408
2409 // Perform this operation as matrix-op-matrix.
2410 return this->writeBinaryExpression(leftType, lhs, op, leftType, rhsMatrix,
2411 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002412 }
John Stiles9aeed132020-11-24 17:36:06 -05002413 } else if (rightType.isMatrix()) {
John Stilesa91bf052021-05-17 09:34:03 -04002414 if (op.kind() == Token::Kind::TK_STAR) {
2415 // Matrix-times-vector and matrix-times-scalar have dedicated ops in SPIR-V.
2416 SpvId result = this->nextId(&resultType);
2417 if (leftType.isVector()) {
2418 this->writeInstruction(SpvOpVectorTimesMatrix, this->getType(resultType),
2419 result, lhs, rhs, out);
2420 } else {
2421 SkASSERT(leftType.isScalar());
2422 this->writeInstruction(SpvOpMatrixTimesScalar, this->getType(resultType),
2423 result, rhs, lhs, out);
2424 }
2425 return result;
ethannicholasb3058bd2016-07-01 08:22:01 -07002426 } else {
John Stilesa91bf052021-05-17 09:34:03 -04002427 // Vector-op-matrix is not supported in GLSL/SkSL for non-multiplication ops; we
2428 // expect to have a scalar here.
John Stiles9aeed132020-11-24 17:36:06 -05002429 SkASSERT(leftType.isScalar());
John Stilesa91bf052021-05-17 09:34:03 -04002430
2431 // Splat lhs across an entire matrix so we can reuse the matrix-op-matrix path.
2432 SpvId lhsMatrix = this->writeScalarToMatrixSplat(rightType, lhs, out);
2433
2434 // Perform this operation as matrix-op-matrix.
2435 return this->writeBinaryExpression(rightType, lhsMatrix, op, rightType, rhs,
2436 resultType, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002437 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002438 } else {
Brian Osmancc914522021-09-24 18:58:37 +00002439 fContext.fErrors->error(leftType.fOffset, "unsupported mixed-type expression");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002440 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002441 }
2442 } else {
John Stiles2d4f9592020-10-30 10:29:12 -04002443 operandType = &this->getActualType(leftType);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002444 SkASSERT(*operandType == this->getActualType(rightType));
ethannicholasb3058bd2016-07-01 08:22:01 -07002445 }
John Stiles45990502021-02-16 10:55:27 -05002446 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002447 case Token::Kind::TK_EQEQ: {
John Stiles9aeed132020-11-24 17:36:06 -05002448 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002449 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002450 SpvOpIEqual, SpvOpAll, SpvOpLogicalAnd, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002451 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002452 if (operandType->isStruct()) {
2453 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2454 }
John Stiles35092102021-04-08 23:30:51 -04002455 if (operandType->isArray()) {
2456 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2457 }
John Stiles4a7dc462020-11-25 11:08:08 -05002458 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002459 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002460 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002461 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2462 operandType->columns(),
2463 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002464 } else {
2465 tmpType = &resultType;
2466 }
2467 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002468 SpvOpFOrdEqual, SpvOpIEqual,
2469 SpvOpIEqual, SpvOpLogicalEqual, out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002470 *operandType, SpvOpAll, out);
Ethan Nicholasef653b82017-02-21 13:50:00 -05002471 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002472 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05002473 if (operandType->isMatrix()) {
Ethan Nicholas68990be2017-07-13 09:36:52 -04002474 return this->writeMatrixComparison(*operandType, lhs, rhs, SpvOpFOrdNotEqual,
Ethan Nicholas0df21132018-07-10 09:37:51 -04002475 SpvOpINotEqual, SpvOpAny, SpvOpLogicalOr, out);
Ethan Nicholas68990be2017-07-13 09:36:52 -04002476 }
John Stilesbc5c2a02021-04-08 11:44:53 -04002477 if (operandType->isStruct()) {
2478 return this->writeStructComparison(*operandType, lhs, op, rhs, out);
2479 }
John Stiles35092102021-04-08 23:30:51 -04002480 if (operandType->isArray()) {
2481 return this->writeArrayComparison(*operandType, lhs, op, rhs, out);
2482 }
John Stiles4a7dc462020-11-25 11:08:08 -05002483 [[fallthrough]];
2484 case Token::Kind::TK_LOGICALXOR:
2485 SkASSERT(resultType.isBoolean());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002486 const Type* tmpType;
John Stiles9aeed132020-11-24 17:36:06 -05002487 if (operandType->isVector()) {
John Stiles54e7c052021-01-11 14:22:36 -05002488 tmpType = &fContext.fTypes.fBool->toCompound(fContext,
2489 operandType->columns(),
2490 operandType->rows());
Ethan Nicholas48e24052018-03-14 13:51:39 -04002491 } else {
2492 tmpType = &resultType;
2493 }
2494 return this->foldToBool(this->writeBinaryOperation(*tmpType, *operandType, lhs, rhs,
Ethan Nicholasef653b82017-02-21 13:50:00 -05002495 SpvOpFOrdNotEqual, SpvOpINotEqual,
2496 SpvOpINotEqual, SpvOpLogicalNotEqual,
2497 out),
Ethan Nicholas48e24052018-03-14 13:51:39 -04002498 *operandType, SpvOpAny, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002499 case Token::Kind::TK_GT:
John Stiles4a7dc462020-11-25 11:08:08 -05002500 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002501 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2502 SpvOpFOrdGreaterThan, SpvOpSGreaterThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002503 SpvOpUGreaterThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002504 case Token::Kind::TK_LT:
John Stiles4a7dc462020-11-25 11:08:08 -05002505 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002506 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFOrdLessThan,
ethannicholasb3058bd2016-07-01 08:22:01 -07002507 SpvOpSLessThan, SpvOpULessThan, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002508 case Token::Kind::TK_GTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002509 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002510 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2511 SpvOpFOrdGreaterThanEqual, SpvOpSGreaterThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002512 SpvOpUGreaterThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002513 case Token::Kind::TK_LTEQ:
John Stiles4a7dc462020-11-25 11:08:08 -05002514 SkASSERT(resultType.isBoolean());
Greg Daniel64773e62016-11-22 09:44:03 -05002515 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs,
2516 SpvOpFOrdLessThanEqual, SpvOpSLessThanEqual,
ethannicholasb3058bd2016-07-01 08:22:01 -07002517 SpvOpULessThanEqual, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002518 case Token::Kind::TK_PLUS:
John Stiles9aeed132020-11-24 17:36:06 -05002519 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002520 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002521 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFAdd, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002522 }
Greg Daniel64773e62016-11-22 09:44:03 -05002523 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002524 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002525 case Token::Kind::TK_MINUS:
John Stiles9aeed132020-11-24 17:36:06 -05002526 if (leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas49465b42019-04-17 12:22:21 -04002527 SkASSERT(leftType == rightType);
John Stiles43b593c2021-05-13 22:03:27 -04002528 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFSub, out);
Ethan Nicholas0df21132018-07-10 09:37:51 -04002529 }
Greg Daniel64773e62016-11-22 09:44:03 -05002530 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002531 SpvOpISub, SpvOpISub, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002532 case Token::Kind::TK_STAR:
John Stiles9aeed132020-11-24 17:36:06 -05002533 if (leftType.isMatrix() && rightType.isMatrix()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002534 // matrix multiply
Ethan Nicholas7f015882021-03-23 14:16:52 -04002535 SpvId result = this->nextId(&resultType);
ethannicholasb3058bd2016-07-01 08:22:01 -07002536 this->writeInstruction(SpvOpMatrixTimesMatrix, this->getType(resultType), result,
2537 lhs, rhs, out);
2538 return result;
2539 }
Greg Daniel64773e62016-11-22 09:44:03 -05002540 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMul,
ethannicholasb3058bd2016-07-01 08:22:01 -07002541 SpvOpIMul, SpvOpIMul, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002542 case Token::Kind::TK_SLASH:
John Stilesbdf3bb72021-05-17 09:34:23 -04002543 if (leftType.isMatrix() && rightType.isMatrix()) {
2544 SkASSERT(leftType == rightType);
2545 return this->writeComponentwiseMatrixBinary(leftType, lhs, rhs, SpvOpFDiv, out);
2546 }
Greg Daniel64773e62016-11-22 09:44:03 -05002547 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFDiv,
ethannicholasb3058bd2016-07-01 08:22:01 -07002548 SpvOpSDiv, SpvOpUDiv, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002549 case Token::Kind::TK_PERCENT:
Ethan Nicholasb3d0f7c2017-05-17 13:13:21 -04002550 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpFMod,
2551 SpvOpSMod, SpvOpUMod, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002552 case Token::Kind::TK_SHL:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002553 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2554 SpvOpShiftLeftLogical, SpvOpShiftLeftLogical,
2555 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002556 case Token::Kind::TK_SHR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002557 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2558 SpvOpShiftRightArithmetic, SpvOpShiftRightLogical,
2559 SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002560 case Token::Kind::TK_BITWISEAND:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002561 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2562 SpvOpBitwiseAnd, SpvOpBitwiseAnd, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002563 case Token::Kind::TK_BITWISEOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002564 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2565 SpvOpBitwiseOr, SpvOpBitwiseOr, SpvOpUndef, out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002566 case Token::Kind::TK_BITWISEXOR:
Ethan Nicholasfd444be2017-07-05 10:05:54 -04002567 return this->writeBinaryOperation(resultType, *operandType, lhs, rhs, SpvOpUndef,
2568 SpvOpBitwiseXor, SpvOpBitwiseXor, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002569 default:
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002570 fContext.fErrors->error(0, "unsupported token");
Ethan Nicholas49465b42019-04-17 12:22:21 -04002571 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002572 }
2573}
2574
John Stiles35092102021-04-08 23:30:51 -04002575SpvId SPIRVCodeGenerator::writeArrayComparison(const Type& arrayType, SpvId lhs, Operator op,
2576 SpvId rhs, OutputStream& out) {
2577 // The inputs must be arrays, and the op must be == or !=.
2578 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
2579 SkASSERT(arrayType.isArray());
2580 const Type& componentType = arrayType.componentType();
2581 const SpvId componentTypeId = this->getType(componentType);
2582 const int arraySize = arrayType.columns();
2583 SkASSERT(arraySize > 0);
2584
2585 // Synthesize equality checks for each item in the array.
2586 const Type& boolType = *fContext.fTypes.fBool;
2587 SpvId allComparisons = (SpvId)-1;
2588 for (int index = 0; index < arraySize; ++index) {
2589 // Get the left and right item in the array.
2590 SpvId itemL = this->nextId(&componentType);
2591 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemL, lhs, index, out);
2592 SpvId itemR = this->nextId(&componentType);
2593 this->writeInstruction(SpvOpCompositeExtract, componentTypeId, itemR, rhs, index, out);
2594 // Use `writeBinaryExpression` with the requested == or != operator on these items.
2595 SpvId comparison = this->writeBinaryExpression(componentType, itemL, op,
2596 componentType, itemR, boolType, out);
2597 // Merge this comparison result with all the other comparisons we've done.
2598 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
2599 }
2600 return allComparisons;
2601}
2602
John Stilesbc5c2a02021-04-08 11:44:53 -04002603SpvId SPIRVCodeGenerator::writeStructComparison(const Type& structType, SpvId lhs, Operator op,
2604 SpvId rhs, OutputStream& out) {
2605 // The inputs must be structs containing fields, and the op must be == or !=.
John Stilesbc5c2a02021-04-08 11:44:53 -04002606 SkASSERT(op.kind() == Token::Kind::TK_EQEQ || op.kind() == Token::Kind::TK_NEQ);
John Stiles35092102021-04-08 23:30:51 -04002607 SkASSERT(structType.isStruct());
John Stilesbc5c2a02021-04-08 11:44:53 -04002608 const std::vector<Type::Field>& fields = structType.fields();
2609 SkASSERT(!fields.empty());
2610
2611 // Synthesize equality checks for each field in the struct.
2612 const Type& boolType = *fContext.fTypes.fBool;
John Stilesbc5c2a02021-04-08 11:44:53 -04002613 SpvId allComparisons = (SpvId)-1;
2614 for (int index = 0; index < (int)fields.size(); ++index) {
2615 // Get the left and right versions of this field.
2616 const Type& fieldType = *fields[index].fType;
John Stiles35092102021-04-08 23:30:51 -04002617 const SpvId fieldTypeId = this->getType(fieldType);
John Stilesbc5c2a02021-04-08 11:44:53 -04002618
2619 SpvId fieldL = this->nextId(&fieldType);
2620 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldL, lhs, index, out);
2621 SpvId fieldR = this->nextId(&fieldType);
2622 this->writeInstruction(SpvOpCompositeExtract, fieldTypeId, fieldR, rhs, index, out);
2623 // Use `writeBinaryExpression` with the requested == or != operator on these fields.
2624 SpvId comparison = this->writeBinaryExpression(fieldType, fieldL, op, fieldType, fieldR,
2625 boolType, out);
John Stiles35092102021-04-08 23:30:51 -04002626 // Merge this comparison result with all the other comparisons we've done.
2627 allComparisons = this->mergeComparisons(comparison, allComparisons, op, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002628 }
2629 return allComparisons;
2630}
2631
John Stiles35092102021-04-08 23:30:51 -04002632SpvId SPIRVCodeGenerator::mergeComparisons(SpvId comparison, SpvId allComparisons, Operator op,
2633 OutputStream& out) {
2634 // If this is the first entry, we don't need to merge comparison results with anything.
2635 if (allComparisons == (SpvId)-1) {
2636 return comparison;
2637 }
2638 // Use LogicalAnd or LogicalOr to combine the comparison with all the other comparisons.
2639 const Type& boolType = *fContext.fTypes.fBool;
2640 SpvId boolTypeId = this->getType(boolType);
2641 SpvId logicalOp = this->nextId(&boolType);
2642 switch (op.kind()) {
2643 case Token::Kind::TK_EQEQ:
2644 this->writeInstruction(SpvOpLogicalAnd, boolTypeId, logicalOp,
2645 comparison, allComparisons, out);
2646 break;
2647 case Token::Kind::TK_NEQ:
2648 this->writeInstruction(SpvOpLogicalOr, boolTypeId, logicalOp,
2649 comparison, allComparisons, out);
2650 break;
2651 default:
2652 SkDEBUGFAILF("mergeComparisons only supports == and !=, not %s", op.operatorName());
2653 return (SpvId)-1;
2654 }
2655 return logicalOp;
2656}
2657
John Stilesbc5c2a02021-04-08 11:44:53 -04002658static float division_by_literal_value(Operator op, const Expression& right) {
2659 // If this is a division by a literal value, returns that literal value. Otherwise, returns 0.
John Stiles7591d4b2021-09-13 13:32:06 -04002660 if (op.kind() == Token::Kind::TK_SLASH && right.isFloatLiteral()) {
2661 float rhsValue = right.as<Literal>().floatValue();
John Stilesbc5c2a02021-04-08 11:44:53 -04002662 if (std::isfinite(rhsValue)) {
2663 return rhsValue;
2664 }
2665 }
2666 return 0.0f;
2667}
2668
Ethan Nicholas49465b42019-04-17 12:22:21 -04002669SpvId SPIRVCodeGenerator::writeBinaryExpression(const BinaryExpression& b, OutputStream& out) {
John Stiles2396fb82021-03-25 11:44:55 -04002670 const Expression* left = b.left().get();
2671 const Expression* right = b.right().get();
John Stiles45990502021-02-16 10:55:27 -05002672 Operator op = b.getOperator();
John Stilesbc5c2a02021-04-08 11:44:53 -04002673
John Stiles45990502021-02-16 10:55:27 -05002674 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002675 case Token::Kind::TK_EQ: {
John Stilesbc5c2a02021-04-08 11:44:53 -04002676 // Handles assignment.
John Stiles2396fb82021-03-25 11:44:55 -04002677 SpvId rhs = this->writeExpression(*right, out);
2678 this->getLValue(*left, out)->store(rhs, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002679 return rhs;
2680 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002681 case Token::Kind::TK_LOGICALAND:
John Stilesbc5c2a02021-04-08 11:44:53 -04002682 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2683 return this->writeLogicalAnd(*b.left(), *b.right(), out);
2684
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002685 case Token::Kind::TK_LOGICALOR:
John Stilesbc5c2a02021-04-08 11:44:53 -04002686 // Handles short-circuiting; we don't necessarily evaluate both LHS and RHS.
2687 return this->writeLogicalOr(*b.left(), *b.right(), out);
2688
Ethan Nicholas49465b42019-04-17 12:22:21 -04002689 default:
2690 break;
2691 }
2692
2693 std::unique_ptr<LValue> lvalue;
2694 SpvId lhs;
John Stiles45990502021-02-16 10:55:27 -05002695 if (op.isAssignment()) {
John Stiles2396fb82021-03-25 11:44:55 -04002696 lvalue = this->getLValue(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002697 lhs = lvalue->load(out);
2698 } else {
2699 lvalue = nullptr;
John Stiles2396fb82021-03-25 11:44:55 -04002700 lhs = this->writeExpression(*left, out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002701 }
John Stiles2396fb82021-03-25 11:44:55 -04002702
John Stilesbc5c2a02021-04-08 11:44:53 -04002703 SpvId rhs;
2704 float rhsValue = division_by_literal_value(op, *right);
2705 if (rhsValue != 0.0f) {
2706 // Rewrite floating-point division by a literal into multiplication by the reciprocal.
2707 // This converts `expr / 2` into `expr * 0.5`
2708 // This improves codegen, especially for certain types of divides (e.g. vector/scalar).
2709 op = Operator(Token::Kind::TK_STAR);
Brian Osmancc914522021-09-24 18:58:37 +00002710 Literal reciprocal{right->fOffset, 1.0f / rhsValue, &right->type()};
John Stilesbc5c2a02021-04-08 11:44:53 -04002711 rhs = this->writeExpression(reciprocal, out);
2712 } else {
2713 // Write the right-hand side expression normally.
John Stiles2396fb82021-03-25 11:44:55 -04002714 rhs = this->writeExpression(*right, out);
2715 }
2716
2717 SpvId result = this->writeBinaryExpression(left->type(), lhs, op.removeAssignment(),
2718 right->type(), rhs, b.type(), out);
Ethan Nicholas49465b42019-04-17 12:22:21 -04002719 if (lvalue) {
2720 lvalue->store(result, out);
2721 }
2722 return result;
2723}
2724
John Stilesbc5c2a02021-04-08 11:44:53 -04002725SpvId SPIRVCodeGenerator::writeLogicalAnd(const Expression& left, const Expression& right,
2726 OutputStream& out) {
Brian Osmancc914522021-09-24 18:58:37 +00002727 Literal falseLiteral(/*offset=*/-1, /*value=*/false, fContext.fTypes.fBool.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002728 SpvId falseConstant = this->writeLiteral(falseLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002729 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002730 SpvId rhsLabel = this->nextId(nullptr);
2731 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002732 SpvId lhsBlock = fCurrentBlock;
2733 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2734 this->writeInstruction(SpvOpBranchConditional, lhs, rhsLabel, end, out);
2735 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002736 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002737 SpvId rhsBlock = fCurrentBlock;
2738 this->writeInstruction(SpvOpBranch, end, out);
2739 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002740 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002741 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, falseConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002742 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002743 return result;
2744}
2745
John Stilesbc5c2a02021-04-08 11:44:53 -04002746SpvId SPIRVCodeGenerator::writeLogicalOr(const Expression& left, const Expression& right,
2747 OutputStream& out) {
Brian Osmancc914522021-09-24 18:58:37 +00002748 Literal trueLiteral(/*offset=*/-1, /*value=*/true, fContext.fTypes.fBool.get());
John Stiles7591d4b2021-09-13 13:32:06 -04002749 SpvId trueConstant = this->writeLiteral(trueLiteral);
John Stilesbc5c2a02021-04-08 11:44:53 -04002750 SpvId lhs = this->writeExpression(left, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002751 SpvId rhsLabel = this->nextId(nullptr);
2752 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002753 SpvId lhsBlock = fCurrentBlock;
2754 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2755 this->writeInstruction(SpvOpBranchConditional, lhs, end, rhsLabel, out);
2756 this->writeLabel(rhsLabel, out);
John Stilesbc5c2a02021-04-08 11:44:53 -04002757 SpvId rhs = this->writeExpression(right, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002758 SpvId rhsBlock = fCurrentBlock;
2759 this->writeInstruction(SpvOpBranch, end, out);
2760 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002761 SpvId result = this->nextId(nullptr);
John Stiles54e7c052021-01-11 14:22:36 -05002762 this->writeInstruction(SpvOpPhi, this->getType(*fContext.fTypes.fBool), result, trueConstant,
ethannicholasd598f792016-07-25 10:08:54 -07002763 lhsBlock, rhs, rhsBlock, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002764 return result;
2765}
2766
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002767SpvId SPIRVCodeGenerator::writeTernaryExpression(const TernaryExpression& t, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002768 const Type& type = t.type();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002769 SpvId test = this->writeExpression(*t.test(), out);
2770 if (t.ifTrue()->type().columns() == 1 &&
2771 t.ifTrue()->isCompileTimeConstant() &&
2772 t.ifFalse()->isCompileTimeConstant()) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002773 // both true and false are constants, can just use OpSelect
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002774 SpvId result = this->nextId(nullptr);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002775 SpvId trueId = this->writeExpression(*t.ifTrue(), out);
2776 SpvId falseId = this->writeExpression(*t.ifFalse(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002777 this->writeInstruction(SpvOpSelect, this->getType(type), result, test, trueId, falseId,
ethannicholasb3058bd2016-07-01 08:22:01 -07002778 out);
2779 return result;
2780 }
Greg Daniel64773e62016-11-22 09:44:03 -05002781 // was originally using OpPhi to choose the result, but for some reason that is crashing on
ethannicholasb3058bd2016-07-01 08:22:01 -07002782 // Adreno. Switched to storing the result in a temp variable as glslang does.
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002783 SpvId var = this->nextId(nullptr);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002784 this->writeInstruction(SpvOpVariable, this->getPointerType(type, SpvStorageClassFunction),
ethannicholasd598f792016-07-25 10:08:54 -07002785 var, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002786 SpvId trueLabel = this->nextId(nullptr);
2787 SpvId falseLabel = this->nextId(nullptr);
2788 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07002789 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
2790 this->writeInstruction(SpvOpBranchConditional, test, trueLabel, falseLabel, out);
2791 this->writeLabel(trueLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002792 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifTrue(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002793 this->writeInstruction(SpvOpBranch, end, out);
2794 this->writeLabel(falseLabel, out);
Ethan Nicholasdd218162020-10-08 05:48:01 -04002795 this->writeInstruction(SpvOpStore, var, this->writeExpression(*t.ifFalse(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002796 this->writeInstruction(SpvOpBranch, end, out);
2797 this->writeLabel(end, out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002798 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002799 this->writeInstruction(SpvOpLoad, this->getType(type), result, var, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002800 return result;
2801}
2802
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002803SpvId SPIRVCodeGenerator::writePrefixExpression(const PrefixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002804 const Type& type = p.type();
John Stiles45990502021-02-16 10:55:27 -05002805 if (p.getOperator().kind() == Token::Kind::TK_MINUS) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002806 SpvId result = this->nextId(&type);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002807 SpvId typeId = this->getType(type);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002808 SpvId expr = this->writeExpression(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002809 if (is_float(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002810 this->writeInstruction(SpvOpFNegate, typeId, result, expr, out);
John Stiles43ac7e62021-08-25 12:43:22 -04002811 } else if (is_signed(fContext, type) || is_unsigned(fContext, type)) {
ethannicholasb3058bd2016-07-01 08:22:01 -07002812 this->writeInstruction(SpvOpSNegate, typeId, result, expr, out);
2813 } else {
John Stileseada7bc2021-02-02 16:29:32 -05002814 SkDEBUGFAILF("unsupported prefix expression %s", p.description().c_str());
Brian Salomon23356442018-11-30 15:33:19 -05002815 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002816 return result;
2817 }
John Stiles45990502021-02-16 10:55:27 -05002818 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002819 case Token::Kind::TK_PLUS:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002820 return this->writeExpression(*p.operand(), out);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002821 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002822 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002823 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2824 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one,
Greg Daniel64773e62016-11-22 09:44:03 -05002825 SpvOpFAdd, SpvOpIAdd, SpvOpIAdd, SpvOpUndef,
ethannicholasb3058bd2016-07-01 08:22:01 -07002826 out);
2827 lv->store(result, out);
2828 return result;
2829 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002830 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002831 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002832 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
2833 SpvId result = this->writeBinaryOperation(type, type, lv->load(out), one, SpvOpFSub,
2834 SpvOpISub, SpvOpISub, SpvOpUndef, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002835 lv->store(result, out);
2836 return result;
2837 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002838 case Token::Kind::TK_LOGICALNOT: {
John Stiles4a7dc462020-11-25 11:08:08 -05002839 SkASSERT(p.operand()->type().isBoolean());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002840 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002841 this->writeInstruction(SpvOpLogicalNot, this->getType(type), result,
2842 this->writeExpression(*p.operand(), out), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002843 return result;
2844 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002845 case Token::Kind::TK_BITWISENOT: {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002846 SpvId result = this->nextId(nullptr);
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002847 this->writeInstruction(SpvOpNot, this->getType(type), result,
2848 this->writeExpression(*p.operand(), out), out);
ethannicholas5961bc92016-10-12 06:39:56 -07002849 return result;
2850 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002851 default:
John Stileseada7bc2021-02-02 16:29:32 -05002852 SkDEBUGFAILF("unsupported prefix expression: %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002853 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002854 }
2855}
2856
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002857SpvId SPIRVCodeGenerator::writePostfixExpression(const PostfixExpression& p, OutputStream& out) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002858 const Type& type = p.type();
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002859 std::unique_ptr<LValue> lv = this->getLValue(*p.operand(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002860 SpvId result = lv->load(out);
Ethan Nicholas30d30222020-09-11 12:27:26 -04002861 SpvId one = this->writeExpression(*create_literal_1(fContext, type), out);
John Stiles45990502021-02-16 10:55:27 -05002862 switch (p.getOperator().kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002863 case Token::Kind::TK_PLUSPLUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002864 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFAdd,
ethannicholasb3058bd2016-07-01 08:22:01 -07002865 SpvOpIAdd, SpvOpIAdd, SpvOpUndef, out);
2866 lv->store(temp, out);
2867 return result;
2868 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04002869 case Token::Kind::TK_MINUSMINUS: {
Ethan Nicholas30d30222020-09-11 12:27:26 -04002870 SpvId temp = this->writeBinaryOperation(type, type, result, one, SpvOpFSub,
ethannicholasb3058bd2016-07-01 08:22:01 -07002871 SpvOpISub, SpvOpISub, SpvOpUndef, out);
2872 lv->store(temp, out);
2873 return result;
2874 }
2875 default:
John Stileseada7bc2021-02-02 16:29:32 -05002876 SkDEBUGFAILF("unsupported postfix expression %s", p.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002877 return -1;
ethannicholasb3058bd2016-07-01 08:22:01 -07002878 }
2879}
2880
John Stiles7591d4b2021-09-13 13:32:06 -04002881SpvId SPIRVCodeGenerator::writeLiteral(const Literal& l) {
2882 int32_t valueBits;
2883 if (l.isFloatLiteral()) {
2884 float value = l.floatValue();
2885 memcpy(&valueBits, &value, sizeof(valueBits));
2886 } else if (l.isIntLiteral()) {
2887 // intValue() returns a 64-bit signed value, which will be truncated here.
2888 // The hash key also contains the numberKind, so -1 won't overlap with 0xFFFFFFFFu.
2889 valueBits = l.intValue();
ethannicholasb3058bd2016-07-01 08:22:01 -07002890 } else {
John Stiles7591d4b2021-09-13 13:32:06 -04002891 valueBits = l.boolValue();
2892 }
2893
2894 SPIRVNumberConstant key{valueBits, l.type().numberKind()};
2895 auto [iter, newlyCreated] = fNumberConstants.insert({key, (SpvId)-1});
2896 if (newlyCreated) {
2897 SpvId result = this->nextId(nullptr);
2898 iter->second = result;
2899
2900 if (l.isBoolLiteral()) {
2901 this->writeInstruction(l.boolValue() ? SpvOpConstantTrue : SpvOpConstantFalse,
2902 this->getType(l.type()), result, fConstantBuffer);
2903 } else {
2904 this->writeInstruction(SpvOpConstant, this->getType(l.type()), result,
2905 (SpvId)valueBits, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07002906 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002907 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002908
John Stilesacb091f2021-01-06 11:57:58 -05002909 return iter->second;
ethannicholasb3058bd2016-07-01 08:22:01 -07002910}
2911
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002912SpvId SPIRVCodeGenerator::writeFunctionStart(const FunctionDeclaration& f, OutputStream& out) {
ethannicholasd598f792016-07-25 10:08:54 -07002913 SpvId result = fFunctionMap[&f];
John Stilesb5db4822021-01-21 13:04:40 -05002914 SpvId returnTypeId = this->getType(f.returnType());
2915 SpvId functionTypeId = this->getFunctionType(f);
2916 this->writeInstruction(SpvOpFunction, returnTypeId, result,
2917 SpvFunctionControlMaskNone, functionTypeId, out);
John Stilesf9e85512021-03-22 12:05:31 -04002918 String mangledName = f.mangledName();
2919 this->writeInstruction(SpvOpName,
2920 result,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002921 skstd::string_view(mangledName.c_str(), mangledName.size()),
John Stilesf9e85512021-03-22 12:05:31 -04002922 fNameBuffer);
2923 for (const Variable* parameter : f.parameters()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002924 SpvId id = this->nextId(nullptr);
John Stilesf9e85512021-03-22 12:05:31 -04002925 fVariableMap[parameter] = id;
2926 SpvId type = this->getPointerType(parameter->type(), SpvStorageClassFunction);
ethannicholasb3058bd2016-07-01 08:22:01 -07002927 this->writeInstruction(SpvOpFunctionParameter, type, id, out);
2928 }
2929 return result;
2930}
2931
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002932SpvId SPIRVCodeGenerator::writeFunction(const FunctionDefinition& f, OutputStream& out) {
2933 fVariableBuffer.reset();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002934 SpvId result = this->writeFunctionStart(f.declaration(), out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05002935 fCurrentBlock = 0;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04002936 this->writeLabel(this->nextId(nullptr), out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002937 StringStream bodyBuffer;
John Stiles0693fb82021-01-22 18:27:52 -05002938 this->writeBlock(f.body()->as<Block>(), bodyBuffer);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002939 write_stringstream(fVariableBuffer, out);
John Stilese8da4d22021-03-24 09:19:45 -04002940 if (f.declaration().isMain()) {
Ethan Nicholas8eb64d32018-12-21 14:50:42 -05002941 write_stringstream(fGlobalInitializersBuffer, out);
2942 }
Ethan Nicholas0df1b042017-03-31 13:56:23 -04002943 write_stringstream(bodyBuffer, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07002944 if (fCurrentBlock) {
John Stiles2558c462021-03-16 17:49:20 -04002945 if (f.declaration().returnType().isVoid()) {
Ethan Nicholas70a44b22017-11-30 09:09:16 -05002946 this->writeInstruction(SpvOpReturn, out);
2947 } else {
2948 this->writeInstruction(SpvOpUnreachable, out);
2949 }
ethannicholasb3058bd2016-07-01 08:22:01 -07002950 }
2951 this->writeInstruction(SpvOpFunctionEnd, out);
2952 return result;
2953}
2954
2955void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target) {
2956 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002957 this->writeInstruction(SpvOpDecorate, target, SpvDecorationLocation, layout.fLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002958 fDecorationBuffer);
2959 }
2960 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002961 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBinding, layout.fBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002962 fDecorationBuffer);
2963 }
2964 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002965 this->writeInstruction(SpvOpDecorate, target, SpvDecorationIndex, layout.fIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002966 fDecorationBuffer);
2967 }
2968 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002969 this->writeInstruction(SpvOpDecorate, target, SpvDecorationDescriptorSet, layout.fSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002970 fDecorationBuffer);
2971 }
Greg Daniel64773e62016-11-22 09:44:03 -05002972 if (layout.fInputAttachmentIndex >= 0) {
2973 this->writeInstruction(SpvOpDecorate, target, SpvDecorationInputAttachmentIndex,
2974 layout.fInputAttachmentIndex, fDecorationBuffer);
Ethan Nicholasbe1099f2018-01-11 16:09:05 -05002975 fCapabilities |= (((uint64_t) 1) << SpvCapabilityInputAttachment);
Greg Daniel64773e62016-11-22 09:44:03 -05002976 }
Brian Osman99ddd2a2021-08-27 11:21:12 -04002977 if (layout.fBuiltin >= 0 && layout.fBuiltin != SK_FRAGCOLOR_BUILTIN) {
Greg Daniel64773e62016-11-22 09:44:03 -05002978 this->writeInstruction(SpvOpDecorate, target, SpvDecorationBuiltIn, layout.fBuiltin,
ethannicholasb3058bd2016-07-01 08:22:01 -07002979 fDecorationBuffer);
2980 }
2981}
2982
2983void SPIRVCodeGenerator::writeLayout(const Layout& layout, SpvId target, int member) {
2984 if (layout.fLocation >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002985 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationLocation,
ethannicholasb3058bd2016-07-01 08:22:01 -07002986 layout.fLocation, fDecorationBuffer);
2987 }
2988 if (layout.fBinding >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002989 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBinding,
ethannicholasb3058bd2016-07-01 08:22:01 -07002990 layout.fBinding, fDecorationBuffer);
2991 }
2992 if (layout.fIndex >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002993 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationIndex,
ethannicholasb3058bd2016-07-01 08:22:01 -07002994 layout.fIndex, fDecorationBuffer);
2995 }
2996 if (layout.fSet >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05002997 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationDescriptorSet,
ethannicholasb3058bd2016-07-01 08:22:01 -07002998 layout.fSet, fDecorationBuffer);
2999 }
Greg Daniel64773e62016-11-22 09:44:03 -05003000 if (layout.fInputAttachmentIndex >= 0) {
3001 this->writeInstruction(SpvOpDecorate, target, member, SpvDecorationInputAttachmentIndex,
3002 layout.fInputAttachmentIndex, fDecorationBuffer);
3003 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003004 if (layout.fBuiltin >= 0) {
Greg Daniel64773e62016-11-22 09:44:03 -05003005 this->writeInstruction(SpvOpMemberDecorate, target, member, SpvDecorationBuiltIn,
ethannicholasb3058bd2016-07-01 08:22:01 -07003006 layout.fBuiltin, fDecorationBuffer);
3007 }
3008}
3009
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003010MemoryLayout SPIRVCodeGenerator::memoryLayoutForVariable(const Variable& v) const {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003011 bool pushConstant = ((v.modifiers().fLayout.fFlags & Layout::kPushConstant_Flag) != 0);
Brian Osman58ee8982021-02-18 15:39:38 -05003012 return pushConstant ? MemoryLayout(MemoryLayout::k430_Standard) : fDefaultLayout;
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003013}
3014
Brian Salomond8d85b92021-07-07 09:41:17 -04003015SpvId SPIRVCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf, bool appendRTFlip) {
Brian Osman2a4c0fb2021-01-22 13:41:40 -05003016 MemoryLayout memoryLayout = this->memoryLayoutForVariable(intf.variable());
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003017 SpvId result = this->nextId(nullptr);
Brian Salomond8d85b92021-07-07 09:41:17 -04003018 const Variable& intfVar = intf.variable();
3019 const Type& type = intfVar.type();
3020 if (!MemoryLayout::LayoutIsSupported(type)) {
Brian Osmancc914522021-09-24 18:58:37 +00003021 fContext.fErrors->error(type.fOffset, "type '" + type.name() + "' is not permitted here");
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003022 return this->nextId(nullptr);
John Stiles0023c0c2020-11-16 13:32:18 -05003023 }
John Stiles9485b552021-01-27 11:47:00 -05003024 SpvStorageClass_ storageClass = get_storage_class(intf.variable(), SpvStorageClassFunction);
John Stilesded41aa2021-08-05 12:19:35 -04003025 if (fProgram.fInputs.fUseFlipRTUniform && appendRTFlip && type.isStruct()) {
Brian Salomond8d85b92021-07-07 09:41:17 -04003026 // We can only have one interface block (because we use push_constant and that is limited
3027 // to one per program), so we need to append rtflip to this one rather than synthesize an
3028 // entirely new block when the variable is referenced. And we can't modify the existing
3029 // block, so we instead create a modified copy of it and write that.
3030 std::vector<Type::Field> fields = type.fields();
3031 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3032 /*location=*/-1,
3033 fProgram.fConfig->fSettings.fRTFlipOffset,
3034 /*binding=*/-1,
3035 /*index=*/-1,
3036 /*set=*/-1,
3037 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003038 /*inputAttachmentIndex=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003039 /*flags=*/0),
3040 SKSL_RTFLIP_NAME,
3041 fContext.fTypes.fFloat2.get());
John Stiles0cac5ed2021-08-06 11:40:39 -04003042 {
3043 AutoAttachPoolToThread attach(fProgram.fPool.get());
3044 const Type* rtFlipStructType = fProgram.fSymbols->takeOwnershipOfSymbol(
Brian Osmancc914522021-09-24 18:58:37 +00003045 Type::MakeStructType(type.fOffset, type.name(), std::move(fields)));
John Stiles0cac5ed2021-08-06 11:40:39 -04003046 const Variable* modifiedVar = fProgram.fSymbols->takeOwnershipOfSymbol(
Brian Osmancc914522021-09-24 18:58:37 +00003047 std::make_unique<Variable>(intfVar.fOffset,
John Stiles0cac5ed2021-08-06 11:40:39 -04003048 &intfVar.modifiers(),
3049 intfVar.name(),
3050 rtFlipStructType,
3051 intfVar.isBuiltin(),
3052 intfVar.storage()));
3053 fSPIRVBonusVariables.insert(modifiedVar);
Brian Osmancc914522021-09-24 18:58:37 +00003054 InterfaceBlock modifiedCopy(intf.fOffset,
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003055 *modifiedVar,
John Stiles0cac5ed2021-08-06 11:40:39 -04003056 intf.typeName(),
3057 intf.instanceName(),
3058 intf.arraySize(),
3059 intf.typeOwner());
3060 result = this->writeInterfaceBlock(modifiedCopy, false);
3061 fProgram.fSymbols->add(std::make_unique<Field>(
Brian Osmancc914522021-09-24 18:58:37 +00003062 /*offset=*/-1, modifiedVar, rtFlipStructType->fields().size() - 1));
Brian Salomond8d85b92021-07-07 09:41:17 -04003063 }
3064 fVariableMap[&intfVar] = result;
3065 fWroteRTFlip = true;
3066 return result;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003067 }
Brian Salomond8d85b92021-07-07 09:41:17 -04003068 const Modifiers& intfModifiers = intfVar.modifiers();
Brian Osman99ddd2a2021-08-27 11:21:12 -04003069 SpvId typeId = this->getType(type, memoryLayout);
Brian Osman58ee8982021-02-18 15:39:38 -05003070 if (intfModifiers.fLayout.fBuiltin == -1) {
Ethan Nicholas6ac8d362019-01-22 21:43:55 +00003071 this->writeInstruction(SpvOpDecorate, typeId, SpvDecorationBlock, fDecorationBuffer);
Ethan Nicholas0dd30d92017-05-01 16:57:07 -04003072 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003073 SpvId ptrType = this->nextId(nullptr);
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003074 this->writeInstruction(SpvOpTypePointer, ptrType, storageClass, typeId, fConstantBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003075 this->writeInstruction(SpvOpVariable, ptrType, result, storageClass, fConstantBuffer);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04003076 Layout layout = intfModifiers.fLayout;
3077 if (intfModifiers.fFlags & Modifiers::kUniform_Flag && layout.fSet == -1) {
Ethan Nicholas8d2ba442018-03-16 16:40:36 -04003078 layout.fSet = 0;
3079 }
3080 this->writeLayout(layout, result);
Brian Salomond8d85b92021-07-07 09:41:17 -04003081 fVariableMap[&intfVar] = result;
ethannicholasb3058bd2016-07-01 08:22:01 -07003082 return result;
3083}
3084
John Stilesd7437ee2021-08-02 11:56:16 -04003085bool SPIRVCodeGenerator::isDead(const Variable& var) const {
3086 // During SPIR-V code generation, we synthesize some extra bonus variables that don't actually
3087 // exist in the Program at all and aren't tracked by the ProgramUsage. They aren't dead, though.
3088 if (fSPIRVBonusVariables.count(&var)) {
3089 return false;
3090 }
3091 ProgramUsage::VariableCounts counts = fProgram.usage()->get(var);
Brian Osman010ce6a2020-10-19 16:34:10 -04003092 if (counts.fRead || counts.fWrite) {
Chris Dalton2284aab2019-11-15 11:02:24 -07003093 return false;
3094 }
Brian Osmand1f3b972021-03-22 17:03:42 -04003095 // It's not entirely clear what the rules are for eliding interface variables. Generally, it
3096 // causes problems to elide them, even when they're dead.
3097 return !(var.modifiers().fFlags &
3098 (Modifiers::kIn_Flag | Modifiers::kOut_Flag | Modifiers::kUniform_Flag));
Chris Dalton2284aab2019-11-15 11:02:24 -07003099}
3100
John Stilesdbd4e6f2021-02-16 13:29:15 -05003101void SPIRVCodeGenerator::writeGlobalVar(ProgramKind kind, const VarDeclaration& varDecl) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003102 const Variable& var = varDecl.var();
John Stiles0ca2f592021-01-27 10:58:10 -05003103 // 9999 is a sentinel value used in our built-in modules that causes us to ignore these
3104 // declarations, beyond adding them to the symbol table.
3105 constexpr int kBuiltinIgnore = 9999;
3106 if (var.modifiers().fLayout.fBuiltin == kBuiltinIgnore) {
Brian Osmanc0213602020-10-06 14:43:32 -04003107 return;
3108 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003109 if (var.modifiers().fLayout.fBuiltin == SK_FRAGCOLOR_BUILTIN &&
John Stilesdbd4e6f2021-02-16 13:29:15 -05003110 kind != ProgramKind::kFragment) {
John Stiles270cec22021-02-17 12:59:36 -05003111 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Osmanc0213602020-10-06 14:43:32 -04003112 return;
3113 }
John Stilesd7437ee2021-08-02 11:56:16 -04003114 if (this->isDead(var)) {
Brian Osmanc0213602020-10-06 14:43:32 -04003115 return;
3116 }
John Stiles0de76f72021-01-29 09:19:39 -05003117 SpvStorageClass_ storageClass = get_storage_class(var, SpvStorageClassPrivate);
John Stilese40d1662021-01-29 10:08:50 -05003118 if (storageClass == SpvStorageClassUniform) {
3119 // Top-level uniforms are emitted in writeUniformBuffer.
3120 fTopLevelUniforms.push_back(&varDecl);
3121 return;
3122 }
3123 const Type& type = var.type();
John Stilesd8fc95d2021-01-26 16:22:53 -05003124 Layout layout = var.modifiers().fLayout;
John Stilese40d1662021-01-29 10:08:50 -05003125 if (layout.fSet < 0 && storageClass == SpvStorageClassUniformConstant) {
John Stiles270cec22021-02-17 12:59:36 -05003126 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
Brian Osmanc0213602020-10-06 14:43:32 -04003127 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003128 SpvId id = this->nextId(&type);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003129 fVariableMap[&var] = id;
Brian Osman99ddd2a2021-08-27 11:21:12 -04003130 SpvId typeId = this->getPointerType(type, storageClass);
Brian Osmanc0213602020-10-06 14:43:32 -04003131 this->writeInstruction(SpvOpVariable, typeId, id, storageClass, fConstantBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003132 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003133 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04003134 SkASSERT(!fCurrentBlock);
3135 fCurrentBlock = -1;
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003136 SpvId value = this->writeExpression(*varDecl.value(), fGlobalInitializersBuffer);
Brian Osmanc0213602020-10-06 14:43:32 -04003137 this->writeInstruction(SpvOpStore, id, value, fGlobalInitializersBuffer);
3138 fCurrentBlock = 0;
3139 }
John Stilesd8fc95d2021-01-26 16:22:53 -05003140 this->writeLayout(layout, id);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003141 if (var.modifiers().fFlags & Modifiers::kFlat_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003142 this->writeInstruction(SpvOpDecorate, id, SpvDecorationFlat, fDecorationBuffer);
3143 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003144 if (var.modifiers().fFlags & Modifiers::kNoPerspective_Flag) {
Brian Osmanc0213602020-10-06 14:43:32 -04003145 this->writeInstruction(SpvOpDecorate, id, SpvDecorationNoPerspective,
3146 fDecorationBuffer);
ethannicholasb3058bd2016-07-01 08:22:01 -07003147 }
3148}
3149
Brian Osmanc0213602020-10-06 14:43:32 -04003150void SPIRVCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, OutputStream& out) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003151 const Variable& var = varDecl.var();
Ethan Nicholas7f015882021-03-23 14:16:52 -04003152 SpvId id = this->nextId(&var.type());
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003153 fVariableMap[&var] = id;
3154 SpvId type = this->getPointerType(var.type(), SpvStorageClassFunction);
Brian Osmanc0213602020-10-06 14:43:32 -04003155 this->writeInstruction(SpvOpVariable, type, id, SpvStorageClassFunction, fVariableBuffer);
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04003156 this->writeInstruction(SpvOpName, id, var.name(), fNameBuffer);
3157 if (varDecl.value()) {
3158 SpvId value = this->writeExpression(*varDecl.value(), out);
Brian Osmanc0213602020-10-06 14:43:32 -04003159 this->writeInstruction(SpvOpStore, id, value, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003160 }
3161}
3162
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003163void SPIRVCodeGenerator::writeStatement(const Statement& s, OutputStream& out) {
Ethan Nicholase6592142020-09-08 10:22:09 -04003164 switch (s.kind()) {
John Stiles98c1f822020-09-09 14:18:53 -04003165 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04003166 case Statement::Kind::kNop:
Ethan Nicholascb670962017-04-20 19:31:52 -04003167 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003168 case Statement::Kind::kBlock:
John Stiles0693fb82021-01-22 18:27:52 -05003169 this->writeBlock(s.as<Block>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003170 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003171 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04003172 this->writeExpression(*s.as<ExpressionStatement>().expression(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003173 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003174 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04003175 this->writeReturnStatement(s.as<ReturnStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003176 break;
Brian Osmanc0213602020-10-06 14:43:32 -04003177 case Statement::Kind::kVarDeclaration:
3178 this->writeVarDeclaration(s.as<VarDeclaration>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003179 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003180 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04003181 this->writeIfStatement(s.as<IfStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003182 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003183 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04003184 this->writeForStatement(s.as<ForStatement>(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003185 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003186 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04003187 this->writeDoStatement(s.as<DoStatement>(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003189 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04003190 this->writeSwitchStatement(s.as<SwitchStatement>(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003192 case Statement::Kind::kBreak:
ethannicholasb3058bd2016-07-01 08:22:01 -07003193 this->writeInstruction(SpvOpBranch, fBreakTarget.top(), out);
3194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003195 case Statement::Kind::kContinue:
ethannicholasb3058bd2016-07-01 08:22:01 -07003196 this->writeInstruction(SpvOpBranch, fContinueTarget.top(), out);
3197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04003198 case Statement::Kind::kDiscard:
ethannicholasb3058bd2016-07-01 08:22:01 -07003199 this->writeInstruction(SpvOpKill, out);
3200 break;
3201 default:
John Stileseada7bc2021-02-02 16:29:32 -05003202 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05003203 break;
ethannicholasb3058bd2016-07-01 08:22:01 -07003204 }
3205}
3206
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003207void SPIRVCodeGenerator::writeBlock(const Block& b, OutputStream& out) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04003208 for (const std::unique_ptr<Statement>& stmt : b.children()) {
3209 this->writeStatement(*stmt, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003210 }
3211}
3212
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003213void SPIRVCodeGenerator::writeIfStatement(const IfStatement& stmt, OutputStream& out) {
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003214 SpvId test = this->writeExpression(*stmt.test(), out);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003215 SpvId ifTrue = this->nextId(nullptr);
3216 SpvId ifFalse = this->nextId(nullptr);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003217 if (stmt.ifFalse()) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003218 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003219 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3220 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3221 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003222 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003223 if (fCurrentBlock) {
3224 this->writeInstruction(SpvOpBranch, end, out);
3225 }
3226 this->writeLabel(ifFalse, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003227 this->writeStatement(*stmt.ifFalse(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003228 if (fCurrentBlock) {
3229 this->writeInstruction(SpvOpBranch, end, out);
3230 }
3231 this->writeLabel(end, out);
3232 } else {
3233 this->writeInstruction(SpvOpSelectionMerge, ifFalse, SpvSelectionControlMaskNone, out);
3234 this->writeInstruction(SpvOpBranchConditional, test, ifTrue, ifFalse, out);
3235 this->writeLabel(ifTrue, out);
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04003236 this->writeStatement(*stmt.ifTrue(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003237 if (fCurrentBlock) {
3238 this->writeInstruction(SpvOpBranch, ifFalse, out);
3239 }
3240 this->writeLabel(ifFalse, out);
3241 }
3242}
3243
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003244void SPIRVCodeGenerator::writeForStatement(const ForStatement& f, OutputStream& out) {
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003245 if (f.initializer()) {
3246 this->writeStatement(*f.initializer(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003247 }
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003248 SpvId header = this->nextId(nullptr);
3249 SpvId start = this->nextId(nullptr);
3250 SpvId body = this->nextId(nullptr);
3251 SpvId next = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003252 fContinueTarget.push(next);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003253 SpvId end = this->nextId(nullptr);
ethannicholasb3058bd2016-07-01 08:22:01 -07003254 fBreakTarget.push(end);
3255 this->writeInstruction(SpvOpBranch, header, out);
3256 this->writeLabel(header, out);
3257 this->writeInstruction(SpvOpLoopMerge, end, next, SpvLoopControlMaskNone, out);
ethannicholasf789b382016-08-03 12:43:36 -07003258 this->writeInstruction(SpvOpBranch, start, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003259 this->writeLabel(start, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003260 if (f.test()) {
3261 SpvId test = this->writeExpression(*f.test(), out);
ethannicholas22f939e2016-10-13 13:25:34 -07003262 this->writeInstruction(SpvOpBranchConditional, test, body, end, out);
Ethan Nicholas7fb39362020-12-16 15:25:19 -05003263 } else {
3264 this->writeInstruction(SpvOpBranch, body, out);
ethannicholas22f939e2016-10-13 13:25:34 -07003265 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003266 this->writeLabel(body, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003267 this->writeStatement(*f.statement(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003268 if (fCurrentBlock) {
3269 this->writeInstruction(SpvOpBranch, next, out);
3270 }
3271 this->writeLabel(next, out);
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04003272 if (f.next()) {
3273 this->writeExpression(*f.next(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003274 }
3275 this->writeInstruction(SpvOpBranch, header, out);
3276 this->writeLabel(end, out);
3277 fBreakTarget.pop();
3278 fContinueTarget.pop();
3279}
3280
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003281void SPIRVCodeGenerator::writeDoStatement(const DoStatement& d, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003282 SpvId header = this->nextId(nullptr);
3283 SpvId start = this->nextId(nullptr);
3284 SpvId next = this->nextId(nullptr);
3285 SpvId continueTarget = this->nextId(nullptr);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003286 fContinueTarget.push(continueTarget);
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003287 SpvId end = this->nextId(nullptr);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003288 fBreakTarget.push(end);
3289 this->writeInstruction(SpvOpBranch, header, out);
3290 this->writeLabel(header, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003291 this->writeInstruction(SpvOpLoopMerge, end, continueTarget, SpvLoopControlMaskNone, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003292 this->writeInstruction(SpvOpBranch, start, out);
3293 this->writeLabel(start, out);
Ethan Nicholas1fd61162020-09-28 13:14:19 -04003294 this->writeStatement(*d.statement(), out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003295 if (fCurrentBlock) {
3296 this->writeInstruction(SpvOpBranch, next, out);
3297 }
3298 this->writeLabel(next, out);
John Stiles68072a42021-04-16 17:25:55 -04003299 this->writeInstruction(SpvOpBranch, continueTarget, out);
Ethan Nicholas0d997662019-04-08 09:46:01 -04003300 this->writeLabel(continueTarget, out);
John Stiles68072a42021-04-16 17:25:55 -04003301 SpvId test = this->writeExpression(*d.test(), out);
3302 this->writeInstruction(SpvOpBranchConditional, test, header, end, out);
Ethan Nicholasfd146aa2017-01-13 16:40:35 -05003303 this->writeLabel(end, out);
3304 fBreakTarget.pop();
3305 fContinueTarget.pop();
3306}
3307
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003308void SPIRVCodeGenerator::writeSwitchStatement(const SwitchStatement& s, OutputStream& out) {
Ethan Nicholas01b05e52020-10-22 15:53:41 -04003309 SpvId value = this->writeExpression(*s.value(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003310 std::vector<SpvId> labels;
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003311 SpvId end = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003312 SpvId defaultLabel = end;
3313 fBreakTarget.push(end);
3314 int size = 3;
John Stiles2d4f9592020-10-30 10:29:12 -04003315 auto& cases = s.cases();
John Stilesb23a64b2021-03-11 08:27:59 -05003316 for (const std::unique_ptr<Statement>& stmt : cases) {
3317 const SwitchCase& c = stmt->as<SwitchCase>();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003318 SpvId label = this->nextId(nullptr);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003319 labels.push_back(label);
John Stilesb23a64b2021-03-11 08:27:59 -05003320 if (c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003321 size += 2;
3322 } else {
3323 defaultLabel = label;
3324 }
3325 }
3326 labels.push_back(end);
3327 this->writeInstruction(SpvOpSelectionMerge, end, SpvSelectionControlMaskNone, out);
3328 this->writeOpCode(SpvOpSwitch, size, out);
3329 this->writeWord(value, out);
3330 this->writeWord(defaultLabel, out);
John Stiles2d4f9592020-10-30 10:29:12 -04003331 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003332 const SwitchCase& c = cases[i]->as<SwitchCase>();
3333 if (!c.value()) {
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003334 continue;
3335 }
John Stiles7591d4b2021-09-13 13:32:06 -04003336 this->writeWord(c.value()->as<Literal>().intValue(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003337 this->writeWord(labels[i], out);
3338 }
John Stiles2d4f9592020-10-30 10:29:12 -04003339 for (size_t i = 0; i < cases.size(); ++i) {
John Stilesb23a64b2021-03-11 08:27:59 -05003340 const SwitchCase& c = cases[i]->as<SwitchCase>();
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003341 this->writeLabel(labels[i], out);
John Stilesb23a64b2021-03-11 08:27:59 -05003342 this->writeStatement(*c.statement(), out);
Ethan Nicholase92b1b12017-11-13 16:13:21 -05003343 if (fCurrentBlock) {
3344 this->writeInstruction(SpvOpBranch, labels[i + 1], out);
3345 }
3346 }
3347 this->writeLabel(end, out);
3348 fBreakTarget.pop();
3349}
3350
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003351void SPIRVCodeGenerator::writeReturnStatement(const ReturnStatement& r, OutputStream& out) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04003352 if (r.expression()) {
3353 this->writeInstruction(SpvOpReturnValue, this->writeExpression(*r.expression(), out),
ethannicholasb3058bd2016-07-01 08:22:01 -07003354 out);
3355 } else {
3356 this->writeInstruction(SpvOpReturn, out);
3357 }
3358}
3359
John Stilese40d1662021-01-29 10:08:50 -05003360// Given any function, returns the top-level symbol table (OUTSIDE of the function's scope).
3361static std::shared_ptr<SymbolTable> get_top_level_symbol_table(const FunctionDeclaration& anyFunc) {
3362 return anyFunc.definition()->body()->as<Block>().symbolTable()->fParent;
3363}
3364
John Stiles4d6310a2021-01-26 19:58:22 -05003365SPIRVCodeGenerator::EntrypointAdapter SPIRVCodeGenerator::writeEntrypointAdapter(
3366 const FunctionDeclaration& main) {
3367 // Our goal is to synthesize a tiny helper function which looks like this:
3368 // void _entrypoint() { sk_FragColor = main(); }
3369
3370 // Fish a symbol table out of main().
John Stilese40d1662021-01-29 10:08:50 -05003371 std::shared_ptr<SymbolTable> symbolTable = get_top_level_symbol_table(main);
John Stiles4d6310a2021-01-26 19:58:22 -05003372
3373 // Get `sk_FragColor` as a writable reference.
3374 const Symbol* skFragColorSymbol = (*symbolTable)["sk_FragColor"];
3375 SkASSERT(skFragColorSymbol);
3376 const Variable& skFragColorVar = skFragColorSymbol->as<Variable>();
Brian Osmancc914522021-09-24 18:58:37 +00003377 auto skFragColorRef = std::make_unique<VariableReference>(/*offset=*/-1, &skFragColorVar,
John Stiles4d6310a2021-01-26 19:58:22 -05003378 VariableReference::RefKind::kWrite);
3379 // Synthesize a call to the `main()` function.
3380 if (main.returnType() != skFragColorRef->type()) {
Brian Osmancc914522021-09-24 18:58:37 +00003381 fContext.fErrors->error(main.fOffset, "SPIR-V does not support returning '" +
3382 main.returnType().description() + "' from main()");
John Stiles4d6310a2021-01-26 19:58:22 -05003383 return {};
3384 }
Brian Osman716aeb92021-04-21 13:20:00 -04003385 ExpressionArray args;
3386 if (main.parameters().size() == 1) {
3387 if (main.parameters()[0]->type() != *fContext.fTypes.fFloat2) {
Brian Osmancc914522021-09-24 18:58:37 +00003388 fContext.fErrors->error(main.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04003389 "SPIR-V does not support parameter of type '" +
3390 main.parameters()[0]->type().description() + "' to main()");
Brian Osman716aeb92021-04-21 13:20:00 -04003391 return {};
3392 }
John Stiles7591d4b2021-09-13 13:32:06 -04003393 args.push_back(dsl::Float2(0).release());
Brian Osman716aeb92021-04-21 13:20:00 -04003394 }
Brian Osmancc914522021-09-24 18:58:37 +00003395 auto callMainFn = std::make_unique<FunctionCall>(/*offset=*/-1, &main.returnType(), &main,
Brian Osman716aeb92021-04-21 13:20:00 -04003396 std::move(args));
John Stiles4d6310a2021-01-26 19:58:22 -05003397
3398 // Synthesize `skFragColor = main()` as a BinaryExpression.
3399 auto assignmentStmt = std::make_unique<ExpressionStatement>(std::make_unique<BinaryExpression>(
Brian Osmancc914522021-09-24 18:58:37 +00003400 /*offset=*/-1,
John Stiles4d6310a2021-01-26 19:58:22 -05003401 std::move(skFragColorRef),
3402 Token::Kind::TK_EQ,
3403 std::move(callMainFn),
3404 &main.returnType()));
3405
3406 // Function bodies are always wrapped in a Block.
3407 StatementArray entrypointStmts;
3408 entrypointStmts.push_back(std::move(assignmentStmt));
Brian Osmancc914522021-09-24 18:58:37 +00003409 auto entrypointBlock = Block::Make(/*offset=*/-1, std::move(entrypointStmts),
John Stilesbf16b6c2021-03-12 19:24:31 -05003410 symbolTable, /*isScope=*/true);
John Stiles4d6310a2021-01-26 19:58:22 -05003411 // Declare an entrypoint function.
3412 EntrypointAdapter adapter;
3413 adapter.fLayout = {};
3414 adapter.fModifiers = Modifiers{adapter.fLayout, Modifiers::kHasSideEffects_Flag};
3415 adapter.entrypointDecl =
Brian Osmancc914522021-09-24 18:58:37 +00003416 std::make_unique<FunctionDeclaration>(/*offset=*/-1,
John Stiles4d6310a2021-01-26 19:58:22 -05003417 &adapter.fModifiers,
3418 "_entrypoint",
3419 /*parameters=*/std::vector<const Variable*>{},
3420 /*returnType=*/fContext.fTypes.fVoid.get(),
3421 /*builtin=*/false);
3422 // Define it.
John Stiles3b204892021-08-27 17:35:35 -04003423 adapter.entrypointDef = FunctionDefinition::Convert(fContext,
Brian Osmancc914522021-09-24 18:58:37 +00003424 /*offset=*/-1,
John Stiles3b204892021-08-27 17:35:35 -04003425 *adapter.entrypointDecl,
3426 std::move(entrypointBlock),
3427 /*builtin=*/false);
John Stiles4d6310a2021-01-26 19:58:22 -05003428
3429 adapter.entrypointDecl->setDefinition(adapter.entrypointDef.get());
3430 return adapter;
3431}
3432
John Stilese40d1662021-01-29 10:08:50 -05003433void SPIRVCodeGenerator::writeUniformBuffer(std::shared_ptr<SymbolTable> topLevelSymbolTable) {
3434 SkASSERT(!fTopLevelUniforms.empty());
3435 static constexpr char kUniformBufferName[] = "_UniformBuffer";
3436
3437 // Convert the list of top-level uniforms into a matching struct named _UniformBuffer, and build
3438 // a lookup table of variables to UniformBuffer field indices.
3439 std::vector<Type::Field> fields;
3440 fields.reserve(fTopLevelUniforms.size());
3441 fTopLevelUniformMap.reserve(fTopLevelUniforms.size());
3442 for (const VarDeclaration* topLevelUniform : fTopLevelUniforms) {
3443 const Variable* var = &topLevelUniform->var();
3444 fTopLevelUniformMap[var] = (int)fields.size();
3445 fields.emplace_back(var->modifiers(), var->name(), &var->type());
3446 }
Brian Osmancc914522021-09-24 18:58:37 +00003447 fUniformBuffer.fStruct = Type::MakeStructType(/*offset=*/-1, kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003448 std::move(fields));
3449
3450 // Create a global variable to contain this struct.
3451 Layout layout;
John Stiles270cec22021-02-17 12:59:36 -05003452 layout.fBinding = fProgram.fConfig->fSettings.fDefaultUniformBinding;
3453 layout.fSet = fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilese40d1662021-01-29 10:08:50 -05003454 Modifiers modifiers{layout, Modifiers::kUniform_Flag};
3455
3456 fUniformBuffer.fInnerVariable = std::make_unique<Variable>(
Brian Osmancc914522021-09-24 18:58:37 +00003457 /*offset=*/-1, fProgram.fModifiers->add(modifiers), kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003458 fUniformBuffer.fStruct.get(), /*builtin=*/false, Variable::Storage::kGlobal);
3459
3460 // Create an interface block object for this global variable.
3461 fUniformBuffer.fInterfaceBlock = std::make_unique<InterfaceBlock>(
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003462 /*offset=*/-1, *fUniformBuffer.fInnerVariable, kUniformBufferName,
John Stilese40d1662021-01-29 10:08:50 -05003463 kUniformBufferName, /*arraySize=*/0, topLevelSymbolTable);
3464
3465 // Generate an interface block and hold onto its ID.
3466 fUniformBufferId = this->writeInterfaceBlock(*fUniformBuffer.fInterfaceBlock);
3467}
3468
Brian Osmancc914522021-09-24 18:58:37 +00003469void SPIRVCodeGenerator::addRTFlipUniform(int offset) {
Brian Salomond8d85b92021-07-07 09:41:17 -04003470 if (fWroteRTFlip) {
3471 return;
3472 }
3473 // Flip variable hasn't been written yet. This means we don't have an existing
3474 // interface block, so we're free to just synthesize one.
3475 fWroteRTFlip = true;
3476 std::vector<Type::Field> fields;
3477 if (fProgram.fConfig->fSettings.fRTFlipOffset < 0) {
Brian Osmancc914522021-09-24 18:58:37 +00003478 fContext.fErrors->error(offset, "RTFlipOffset is negative");
Brian Salomond8d85b92021-07-07 09:41:17 -04003479 }
3480 fields.emplace_back(Modifiers(Layout(/*flags=*/0,
3481 /*location=*/-1,
3482 fProgram.fConfig->fSettings.fRTFlipOffset,
3483 /*binding=*/-1,
3484 /*index=*/-1,
3485 /*set=*/-1,
3486 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003487 /*inputAttachmentIndex=*/-1),
Brian Salomond8d85b92021-07-07 09:41:17 -04003488 /*flags=*/0),
3489 SKSL_RTFLIP_NAME,
3490 fContext.fTypes.fFloat2.get());
Ethan Nicholas27f06eb2021-07-26 16:39:40 -04003491 skstd::string_view name = "sksl_synthetic_uniforms";
Brian Salomond8d85b92021-07-07 09:41:17 -04003492 const Type* intfStruct =
Brian Osmancc914522021-09-24 18:58:37 +00003493 fSynthetics.takeOwnershipOfSymbol(Type::MakeStructType(/*offset=*/-1, name, fields));
Brian Salomond8d85b92021-07-07 09:41:17 -04003494 int binding = fProgram.fConfig->fSettings.fRTFlipBinding;
3495 if (binding == -1) {
Brian Osmancc914522021-09-24 18:58:37 +00003496 fContext.fErrors->error(offset, "layout(binding=...) is required in SPIR-V");
Brian Salomond8d85b92021-07-07 09:41:17 -04003497 }
3498 int set = fProgram.fConfig->fSettings.fRTFlipSet;
3499 if (set == -1) {
Brian Osmancc914522021-09-24 18:58:37 +00003500 fContext.fErrors->error(offset, "layout(set=...) is required in SPIR-V");
Brian Salomond8d85b92021-07-07 09:41:17 -04003501 }
3502 bool usePushConstants = fProgram.fConfig->fSettings.fUsePushConstants;
3503 int flags = usePushConstants ? Layout::Flag::kPushConstant_Flag : 0;
John Stiles0cac5ed2021-08-06 11:40:39 -04003504 const Modifiers* modsPtr;
3505 {
3506 AutoAttachPoolToThread attach(fProgram.fPool.get());
3507 Modifiers modifiers(Layout(flags,
3508 /*location=*/-1,
3509 /*offset=*/-1,
3510 binding,
3511 /*index=*/-1,
3512 set,
3513 /*builtin=*/-1,
Brian Osman99ddd2a2021-08-27 11:21:12 -04003514 /*inputAttachmentIndex=*/-1),
John Stiles0cac5ed2021-08-06 11:40:39 -04003515 Modifiers::kUniform_Flag);
3516 modsPtr = fProgram.fModifiers->add(modifiers);
Brian Salomond8d85b92021-07-07 09:41:17 -04003517 }
3518 const Variable* intfVar = fSynthetics.takeOwnershipOfSymbol(
Brian Osmancc914522021-09-24 18:58:37 +00003519 std::make_unique<Variable>(/*offset=*/-1,
Brian Salomond8d85b92021-07-07 09:41:17 -04003520 modsPtr,
3521 name,
3522 intfStruct,
3523 /*builtin=*/false,
3524 Variable::Storage::kGlobal));
John Stilesd7437ee2021-08-02 11:56:16 -04003525 fSPIRVBonusVariables.insert(intfVar);
John Stiles0cac5ed2021-08-06 11:40:39 -04003526 {
3527 AutoAttachPoolToThread attach(fProgram.fPool.get());
Brian Osmancc914522021-09-24 18:58:37 +00003528 fProgram.fSymbols->add(std::make_unique<Field>(/*offset=*/-1, intfVar, /*field=*/0));
Brian Salomond8d85b92021-07-07 09:41:17 -04003529 }
Brian Osmancc914522021-09-24 18:58:37 +00003530 InterfaceBlock intf(/*offset=*/-1,
Ethan Nicholas2816dcf2021-09-21 09:18:47 -04003531 *intfVar,
Ethan Nicholas3533ff12021-08-02 12:53:29 -04003532 name,
Brian Salomond8d85b92021-07-07 09:41:17 -04003533 /*instanceName=*/"",
3534 /*arraySize=*/0,
Ethan Nicholasc7774a72021-08-27 15:34:05 -04003535 std::make_shared<SymbolTable>(fContext, /*builtin=*/false));
Brian Salomond8d85b92021-07-07 09:41:17 -04003536
3537 this->writeInterfaceBlock(intf, false);
3538}
3539
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003540void SPIRVCodeGenerator::writeInstructions(const Program& program, OutputStream& out) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003541 fGLSLExtendedInstructions = this->nextId(nullptr);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003542 StringStream body;
John Stiles4d6310a2021-01-26 19:58:22 -05003543 // Assign SpvIds to functions.
3544 const FunctionDeclaration* main = nullptr;
Brian Osman133724c2020-10-28 14:14:39 -04003545 for (const ProgramElement* e : program.elements()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003546 if (e->is<FunctionDefinition>()) {
3547 const FunctionDefinition& funcDef = e->as<FunctionDefinition>();
3548 const FunctionDeclaration& funcDecl = funcDef.declaration();
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003549 fFunctionMap[&funcDecl] = this->nextId(nullptr);
John Stilese8da4d22021-03-24 09:19:45 -04003550 if (funcDecl.isMain()) {
John Stiles4d6310a2021-01-26 19:58:22 -05003551 main = &funcDecl;
Ethan Nicholasb6ba82c2018-01-17 15:21:50 -05003552 }
ethannicholasb3058bd2016-07-01 08:22:01 -07003553 }
3554 }
John Stiles4d6310a2021-01-26 19:58:22 -05003555 // Make sure we have a main() function.
3556 if (!main) {
Ethan Nicholas5fad2b82021-09-27 10:39:18 -04003557 fContext.fErrors->error(/*offset=*/-1, "program does not contain a main() function");
John Stiles4d6310a2021-01-26 19:58:22 -05003558 return;
3559 }
3560 // Emit interface blocks.
3561 std::set<SpvId> interfaceVars;
Brian Osman133724c2020-10-28 14:14:39 -04003562 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003563 if (e->is<InterfaceBlock>()) {
Brian Osman1f8f5752020-10-28 14:46:21 -04003564 const InterfaceBlock& intf = e->as<InterfaceBlock>();
ethannicholasb3058bd2016-07-01 08:22:01 -07003565 SpvId id = this->writeInterfaceBlock(intf);
Brian Osman1f8f5752020-10-28 14:46:21 -04003566
3567 const Modifiers& modifiers = intf.variable().modifiers();
John Stiles8e2a84b2021-04-19 09:35:38 -04003568 if ((modifiers.fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003569 modifiers.fLayout.fBuiltin == -1 && !this->isDead(intf.variable())) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003570 interfaceVars.insert(id);
ethannicholasb3058bd2016-07-01 08:22:01 -07003571 }
3572 }
3573 }
John Stiles4d6310a2021-01-26 19:58:22 -05003574 // Emit global variable declarations.
Brian Osman133724c2020-10-28 14:14:39 -04003575 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003576 if (e->is<GlobalVarDeclaration>()) {
John Stiles270cec22021-02-17 12:59:36 -05003577 this->writeGlobalVar(program.fConfig->fKind,
John Stilese40d1662021-01-29 10:08:50 -05003578 e->as<GlobalVarDeclaration>().declaration()->as<VarDeclaration>());
ethannicholasb3058bd2016-07-01 08:22:01 -07003579 }
3580 }
John Stilese40d1662021-01-29 10:08:50 -05003581 // Emit top-level uniforms into a dedicated uniform buffer.
3582 if (!fTopLevelUniforms.empty()) {
3583 this->writeUniformBuffer(get_top_level_symbol_table(*main));
3584 }
John Stiles4d6310a2021-01-26 19:58:22 -05003585 // If main() returns a half4, synthesize a tiny entrypoint function which invokes the real
3586 // main() and stores the result into sk_FragColor.
3587 EntrypointAdapter adapter;
3588 if (main->returnType() == *fContext.fTypes.fHalf4) {
3589 adapter = this->writeEntrypointAdapter(*main);
3590 if (adapter.entrypointDecl) {
Ethan Nicholas8f352ce2021-03-17 14:12:20 -04003591 fFunctionMap[adapter.entrypointDecl.get()] = this->nextId(nullptr);
John Stiles4d6310a2021-01-26 19:58:22 -05003592 this->writeFunction(*adapter.entrypointDef, body);
3593 main = adapter.entrypointDecl.get();
3594 }
3595 }
3596 // Emit all the functions.
Brian Osman133724c2020-10-28 14:14:39 -04003597 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003598 if (e->is<FunctionDefinition>()) {
3599 this->writeFunction(e->as<FunctionDefinition>(), body);
ethannicholasb3058bd2016-07-01 08:22:01 -07003600 }
3601 }
John Stiles4d6310a2021-01-26 19:58:22 -05003602 // Add global in/out variables to the list of interface variables.
ethannicholasb3058bd2016-07-01 08:22:01 -07003603 for (auto entry : fVariableMap) {
ethannicholasd598f792016-07-25 10:08:54 -07003604 const Variable* var = entry.first;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04003605 if (var->storage() == Variable::Storage::kGlobal &&
John Stiles8e2a84b2021-04-19 09:35:38 -04003606 (var->modifiers().fFlags & (Modifiers::kIn_Flag | Modifiers::kOut_Flag)) &&
John Stilesd7437ee2021-08-02 11:56:16 -04003607 !this->isDead(*var)) {
Ethan Nicholas8e48c1e2017-03-02 14:33:31 -05003608 interfaceVars.insert(entry.second);
ethannicholasb3058bd2016-07-01 08:22:01 -07003609 }
3610 }
3611 this->writeCapabilities(out);
3612 this->writeInstruction(SpvOpExtInstImport, fGLSLExtendedInstructions, "GLSL.std.450", out);
3613 this->writeInstruction(SpvOpMemoryModel, SpvAddressingModelLogical, SpvMemoryModelGLSL450, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003614 this->writeOpCode(SpvOpEntryPoint, (SpvId) (3 + (main->name().length() + 4) / 4) +
ethannicholasb3058bd2016-07-01 08:22:01 -07003615 (int32_t) interfaceVars.size(), out);
John Stiles270cec22021-02-17 12:59:36 -05003616 switch (program.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05003617 case ProgramKind::kVertex:
ethannicholasb3058bd2016-07-01 08:22:01 -07003618 this->writeWord(SpvExecutionModelVertex, out);
3619 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05003620 case ProgramKind::kFragment:
ethannicholasb3058bd2016-07-01 08:22:01 -07003621 this->writeWord(SpvExecutionModelFragment, out);
3622 break;
Ethan Nicholas762466e2017-06-29 10:03:38 -04003623 default:
John Stilesf57207b2021-02-02 17:50:34 -05003624 SK_ABORT("cannot write this kind of program to SPIR-V\n");
ethannicholasb3058bd2016-07-01 08:22:01 -07003625 }
Ethan Nicholasbb155e22017-07-24 10:05:09 -04003626 SpvId entryPoint = fFunctionMap[main];
3627 this->writeWord(entryPoint, out);
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003628 this->writeString(main->name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003629 for (int var : interfaceVars) {
3630 this->writeWord(var, out);
3631 }
John Stiles270cec22021-02-17 12:59:36 -05003632 if (program.fConfig->fKind == ProgramKind::kFragment) {
Greg Daniel64773e62016-11-22 09:44:03 -05003633 this->writeInstruction(SpvOpExecutionMode,
3634 fFunctionMap[main],
ethannicholasb3058bd2016-07-01 08:22:01 -07003635 SpvExecutionModeOriginUpperLeft,
3636 out);
3637 }
Brian Osman133724c2020-10-28 14:14:39 -04003638 for (const ProgramElement* e : program.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04003639 if (e->is<Extension>()) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -04003640 this->writeInstruction(SpvOpSourceExtension, e->as<Extension>().name(), out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003641 }
3642 }
Greg Daniel64773e62016-11-22 09:44:03 -05003643
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003644 write_stringstream(fExtraGlobalsBuffer, out);
3645 write_stringstream(fNameBuffer, out);
3646 write_stringstream(fDecorationBuffer, out);
3647 write_stringstream(fConstantBuffer, out);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003648 write_stringstream(body, out);
ethannicholasb3058bd2016-07-01 08:22:01 -07003649}
3650
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003651bool SPIRVCodeGenerator::generateCode() {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003652 SkASSERT(!fContext.fErrors->errorCount());
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003653 this->writeWord(SpvMagicNumber, *fOut);
3654 this->writeWord(SpvVersion, *fOut);
3655 this->writeWord(SKSL_MAGIC, *fOut);
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003656 StringStream buffer;
Ethan Nicholas941e7e22016-12-12 15:33:30 -05003657 this->writeInstructions(fProgram, buffer);
3658 this->writeWord(fIdCount, *fOut);
3659 this->writeWord(0, *fOut); // reserved, always zero
Ethan Nicholas0df1b042017-03-31 13:56:23 -04003660 write_stringstream(buffer, *fOut);
Ethan Nicholas553239b2021-08-23 15:40:20 -04003661 fContext.fErrors->reportPendingErrors(PositionInfo());
Ethan Nicholas39f6da42021-08-23 13:10:07 -04003662 return fContext.fErrors->errorCount() == 0;
ethannicholasb3058bd2016-07-01 08:22:01 -07003663}
3664
John Stilesa6841be2020-08-06 14:11:56 -04003665} // namespace SkSL