blob: c42061f555b16ab23bc3ea6cfc46e4d94fdf31ee [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLCompiler.h"
11#include "src/sksl/ir/SkSLExpressionStatement.h"
12#include "src/sksl/ir/SkSLExtension.h"
13#include "src/sksl/ir/SkSLIndexExpression.h"
14#include "src/sksl/ir/SkSLModifiersDeclaration.h"
15#include "src/sksl/ir/SkSLNop.h"
16#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040017
Timothy Liangb8eeb802018-07-23 16:46:16 -040018#ifdef SK_MOLTENVK
19 static const uint32_t MVKMagicNum = 0x19960412;
20#endif
Timothy Lianga06f2152018-05-24 15:33:31 -040021
Ethan Nicholascc305772017-10-13 16:17:45 -040022namespace SkSL {
23
Timothy Liangee84fe12018-05-18 14:38:19 -040024void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040025#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
26#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040027 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040028 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050029 fIntrinsicMap[String("equal")] = METAL(Equal);
30 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040031 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
32 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
33 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
34 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040035}
36
Ethan Nicholascc305772017-10-13 16:17:45 -040037void MetalCodeGenerator::write(const char* s) {
38 if (!s[0]) {
39 return;
40 }
41 if (fAtLineStart) {
42 for (int i = 0; i < fIndentation; i++) {
43 fOut->writeText(" ");
44 }
45 }
46 fOut->writeText(s);
47 fAtLineStart = false;
48}
49
50void MetalCodeGenerator::writeLine(const char* s) {
51 this->write(s);
52 fOut->writeText(fLineEnding);
53 fAtLineStart = true;
54}
55
56void MetalCodeGenerator::write(const String& s) {
57 this->write(s.c_str());
58}
59
60void MetalCodeGenerator::writeLine(const String& s) {
61 this->writeLine(s.c_str());
62}
63
64void MetalCodeGenerator::writeLine() {
65 this->writeLine("");
66}
67
68void MetalCodeGenerator::writeExtension(const Extension& ext) {
69 this->writeLine("#extension " + ext.fName + " : enable");
70}
71
Ethan Nicholas45fa8102020-01-13 10:58:49 -050072String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholascc305772017-10-13 16:17:45 -040073 switch (type.kind()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040074 case Type::kVector_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050075 return this->typeName(type.componentType()) + to_string(type.columns());
Timothy Liang43d225f2018-07-19 15:27:13 -040076 case Type::kMatrix_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050077 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
78 to_string(type.rows());
Timothy Liangee84fe12018-05-18 14:38:19 -040079 case Type::kSampler_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050080 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040081 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040082 if (type == *fContext.fHalf_Type) {
83 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040085 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050086 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040087 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050088 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040089 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050090 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040091 }
Ethan Nicholascc305772017-10-13 16:17:45 -040092 }
93}
94
Ethan Nicholas45fa8102020-01-13 10:58:49 -050095void MetalCodeGenerator::writeType(const Type& type) {
96 if (type.kind() == Type::kStruct_Kind) {
97 for (const Type* search : fWrittenStructs) {
98 if (*search == type) {
99 // already written
100 this->write(type.name());
101 return;
102 }
103 }
104 fWrittenStructs.push_back(&type);
105 this->writeLine("struct " + type.name() + " {");
106 fIndentation++;
107 this->writeFields(type.fields(), type.fOffset);
108 fIndentation--;
109 this->write("}");
110 } else {
111 this->write(this->typeName(type));
112 }
113}
114
Ethan Nicholascc305772017-10-13 16:17:45 -0400115void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
116 switch (expr.fKind) {
117 case Expression::kBinary_Kind:
118 this->writeBinaryExpression((BinaryExpression&) expr, parentPrecedence);
119 break;
120 case Expression::kBoolLiteral_Kind:
121 this->writeBoolLiteral((BoolLiteral&) expr);
122 break;
123 case Expression::kConstructor_Kind:
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500124 this->writeConstructor((Constructor&) expr, parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400125 break;
126 case Expression::kIntLiteral_Kind:
127 this->writeIntLiteral((IntLiteral&) expr);
128 break;
129 case Expression::kFieldAccess_Kind:
130 this->writeFieldAccess(((FieldAccess&) expr));
131 break;
132 case Expression::kFloatLiteral_Kind:
133 this->writeFloatLiteral(((FloatLiteral&) expr));
134 break;
135 case Expression::kFunctionCall_Kind:
136 this->writeFunctionCall((FunctionCall&) expr);
137 break;
138 case Expression::kPrefix_Kind:
139 this->writePrefixExpression((PrefixExpression&) expr, parentPrecedence);
140 break;
141 case Expression::kPostfix_Kind:
142 this->writePostfixExpression((PostfixExpression&) expr, parentPrecedence);
143 break;
144 case Expression::kSetting_Kind:
145 this->writeSetting((Setting&) expr);
146 break;
147 case Expression::kSwizzle_Kind:
148 this->writeSwizzle((Swizzle&) expr);
149 break;
150 case Expression::kVariableReference_Kind:
151 this->writeVariableReference((VariableReference&) expr);
152 break;
153 case Expression::kTernary_Kind:
154 this->writeTernaryExpression((TernaryExpression&) expr, parentPrecedence);
155 break;
156 case Expression::kIndex_Kind:
157 this->writeIndexExpression((IndexExpression&) expr);
158 break;
159 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500160#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400161 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500162#endif
163 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400164 }
165}
166
Timothy Liang6403b0e2018-05-17 10:40:04 -0400167void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400168 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400169 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400170 Intrinsic intrinsic = i->second;
171 int32_t intrinsicId = intrinsic.second;
172 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400173 case kSpecial_IntrinsicKind:
174 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400175 break;
176 case kMetal_IntrinsicKind:
177 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
178 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500179 case kEqual_MetalIntrinsic:
180 this->write(" == ");
181 break;
182 case kNotEqual_MetalIntrinsic:
183 this->write(" != ");
184 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400185 case kLessThan_MetalIntrinsic:
186 this->write(" < ");
187 break;
188 case kLessThanEqual_MetalIntrinsic:
189 this->write(" <= ");
190 break;
191 case kGreaterThan_MetalIntrinsic:
192 this->write(" > ");
193 break;
194 case kGreaterThanEqual_MetalIntrinsic:
195 this->write(" >= ");
196 break;
197 default:
198 ABORT("unsupported metal intrinsic kind");
199 }
200 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
201 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400202 default:
203 ABORT("unsupported intrinsic kind");
204 }
205}
206
Ethan Nicholascc305772017-10-13 16:17:45 -0400207void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400208 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
209 if (entry != fIntrinsicMap.end()) {
210 this->writeIntrinsicCall(c);
211 return;
212 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400213 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
214 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400215 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
216 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500217 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
218 SkASSERT(c.fArguments.size() == 1);
219 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400220 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
221 this->write("dfdx");
222 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700223 // Flipping Y also negates the Y derivatives.
224 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400225 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400226 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400227 }
228 this->write("(");
229 const char* separator = "";
230 if (this->requirements(c.fFunction) & kInputs_Requirement) {
231 this->write("_in");
232 separator = ", ";
233 }
234 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
235 this->write(separator);
236 this->write("_out");
237 separator = ", ";
238 }
239 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
240 this->write(separator);
241 this->write("_uniforms");
242 separator = ", ";
243 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400244 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
245 this->write(separator);
246 this->write("_globals");
247 separator = ", ";
248 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400249 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
250 this->write(separator);
251 this->write("_fragCoord");
252 separator = ", ";
253 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400254 for (size_t i = 0; i < c.fArguments.size(); ++i) {
255 const Expression& arg = *c.fArguments[i];
256 this->write(separator);
257 separator = ", ";
258 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
259 this->write("&");
260 }
261 this->writeExpression(arg, kSequence_Precedence);
262 }
263 this->write(")");
264}
265
Chris Daltondba7aab2018-11-15 10:57:49 -0500266void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500267 String typeName = mat.fType.name();
268 String name = typeName + "_inverse";
269 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500270 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
271 fWrittenIntrinsics.insert(name);
272 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500273 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500274 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
275 "}"
276 ).c_str());
277 }
278 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500279 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
280 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
281 fWrittenIntrinsics.insert(name);
282 fExtraFunctions.writeText((
283 typeName + " " + name + "(" + typeName + " m) {"
284 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
285 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
286 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
287 " float b01 = a22 * a11 - a12 * a21;"
288 " float b11 = -a22 * a10 + a12 * a20;"
289 " float b21 = a21 * a10 - a11 * a20;"
290 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
291 " return " + typeName +
292 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
293 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
294 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
295 " (1/det);"
296 "}"
297 ).c_str());
298 }
299 }
300 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
301 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
302 fWrittenIntrinsics.insert(name);
303 fExtraFunctions.writeText((
304 typeName + " " + name + "(" + typeName + " m) {"
305 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
306 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
307 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
308 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
309 " float b00 = a00 * a11 - a01 * a10;"
310 " float b01 = a00 * a12 - a02 * a10;"
311 " float b02 = a00 * a13 - a03 * a10;"
312 " float b03 = a01 * a12 - a02 * a11;"
313 " float b04 = a01 * a13 - a03 * a11;"
314 " float b05 = a02 * a13 - a03 * a12;"
315 " float b06 = a20 * a31 - a21 * a30;"
316 " float b07 = a20 * a32 - a22 * a30;"
317 " float b08 = a20 * a33 - a23 * a30;"
318 " float b09 = a21 * a32 - a22 * a31;"
319 " float b10 = a21 * a33 - a23 * a31;"
320 " float b11 = a22 * a33 - a23 * a32;"
321 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
322 " b04 * b07 + b05 * b06;"
323 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
324 " a02 * b10 - a01 * b11 - a03 * b09,"
325 " a31 * b05 - a32 * b04 + a33 * b03,"
326 " a22 * b04 - a21 * b05 - a23 * b03,"
327 " a12 * b08 - a10 * b11 - a13 * b07,"
328 " a00 * b11 - a02 * b08 + a03 * b07,"
329 " a32 * b02 - a30 * b05 - a33 * b01,"
330 " a20 * b05 - a22 * b02 + a23 * b01,"
331 " a10 * b10 - a11 * b08 + a13 * b06,"
332 " a01 * b08 - a00 * b10 - a03 * b06,"
333 " a30 * b04 - a31 * b02 + a33 * b00,"
334 " a21 * b02 - a20 * b04 - a23 * b00,"
335 " a11 * b07 - a10 * b09 - a12 * b06,"
336 " a00 * b09 - a01 * b07 + a02 * b06,"
337 " a31 * b01 - a30 * b03 - a32 * b00,"
338 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
339 "}"
340 ).c_str());
341 }
342 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500343 this->write(name);
344}
345
Timothy Liang6403b0e2018-05-17 10:40:04 -0400346void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
347 switch (kind) {
348 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400349 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400350 this->write(".sample(");
351 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
352 this->write(SAMPLER_SUFFIX);
353 this->write(", ");
Timothy Liangee84fe12018-05-18 14:38:19 -0400354 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500355 // have to store the vector in a temp variable to avoid double evaluating it
356 String tmpVar = "tmpCoord" + to_string(fVarCount++);
357 this->fFunctionHeader += " " + this->typeName(c.fArguments[1]->fType) + " " +
358 tmpVar + ";\n";
359 this->write("(" + tmpVar + " = ");
360 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
361 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400362 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400363 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500364 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400365 this->write(")");
366 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400367 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500368 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400369 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500370 String tmpX = "tmpX" + to_string(fVarCount++);
371 String tmpY = "tmpY" + to_string(fVarCount++);
372 this->fFunctionHeader += " " + this->typeName(c.fArguments[0]->fType) + " " + tmpX +
373 ", " + tmpY + ";\n";
374 this->write("(" + tmpX + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400375 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500376 this->write(", " + tmpY + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400377 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500378 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400379 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500380 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400381 default:
382 ABORT("unsupported special intrinsic kind");
383 }
384}
385
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500386// If it hasn't already been written, writes a constructor for 'matrix' which takes a single value
387// of type 'arg'.
388String MetalCodeGenerator::getMatrixConstructHelper(const Type& matrix, const Type& arg) {
389 String key = matrix.name() + arg.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500390 auto found = fHelpers.find(key);
391 if (found != fHelpers.end()) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500392 return found->second;
Ethan Nicholascc305772017-10-13 16:17:45 -0400393 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500394 String name;
395 int columns = matrix.columns();
396 int rows = matrix.rows();
397 if (arg.isNumber()) {
398 // creating a matrix from a single scalar value
399 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float";
400 fExtraFunctions.printf("float%dx%d %s(float x) {\n",
401 columns, rows, name.c_str());
402 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
403 for (int i = 0; i < columns; ++i) {
404 if (i > 0) {
405 fExtraFunctions.writeText(", ");
406 }
407 fExtraFunctions.printf("float%d(", rows);
408 for (int j = 0; j < rows; ++j) {
409 if (j > 0) {
410 fExtraFunctions.writeText(", ");
411 }
412 if (i == j) {
413 fExtraFunctions.writeText("x");
414 } else {
415 fExtraFunctions.writeText("0");
416 }
417 }
418 fExtraFunctions.writeText(")");
419 }
420 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500421 } else if (arg.kind() == Type::kMatrix_Kind) {
422 // creating a matrix from another matrix
423 int argColumns = arg.columns();
424 int argRows = arg.rows();
425 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float" +
426 to_string(argColumns) + "x" + to_string(argRows);
427 fExtraFunctions.printf("float%dx%d %s(float%dx%d m) {\n",
428 columns, rows, name.c_str(), argColumns, argRows);
429 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
430 for (int i = 0; i < columns; ++i) {
431 if (i > 0) {
432 fExtraFunctions.writeText(", ");
433 }
434 fExtraFunctions.printf("float%d(", rows);
435 for (int j = 0; j < rows; ++j) {
436 if (j > 0) {
437 fExtraFunctions.writeText(", ");
438 }
439 if (i < argColumns && j < argRows) {
440 fExtraFunctions.printf("m[%d][%d]", i, j);
441 } else {
442 fExtraFunctions.writeText("0");
443 }
444 }
445 fExtraFunctions.writeText(")");
446 }
447 fExtraFunctions.writeText(");\n}\n");
448 } else if (matrix.rows() == 2 && matrix.columns() == 2 && arg == *fContext.fFloat4_Type) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500449 // float2x2(float4) doesn't work, need to split it into float2x2(float2, float2)
450 name = "float2x2_from_float4";
451 fExtraFunctions.printf(
452 "float2x2 %s(float4 v) {\n"
453 " return float2x2(float2(v[0], v[1]), float2(v[2], v[3]));\n"
454 "}\n",
455 name.c_str()
456 );
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500457 } else {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500458 SkASSERT(false);
459 name = "<error>";
460 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500461 fHelpers[key] = name;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500462 return name;
463}
464
465bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
466 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
467 return false;
468 }
469 if (t1.columns() > 1) {
470 return this->canCoerce(t1.componentType(), t2.componentType());
471 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500472 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500473}
474
475void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
476 if (c.fArguments.size() == 1 && this->canCoerce(c.fType, c.fArguments[0]->fType)) {
477 this->writeExpression(*c.fArguments[0], parentPrecedence);
478 return;
479 }
480 if (c.fType.kind() == Type::kMatrix_Kind && c.fArguments.size() == 1) {
481 const Expression& arg = *c.fArguments[0];
482 String name = this->getMatrixConstructHelper(c.fType, arg.fType);
483 this->write(name);
484 this->write("(");
485 this->writeExpression(arg, kSequence_Precedence);
486 this->write(")");
487 } else {
488 this->writeType(c.fType);
489 this->write("(");
490 const char* separator = "";
491 int scalarCount = 0;
492 for (const auto& arg : c.fArguments) {
493 this->write(separator);
494 separator = ", ";
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500495 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() != c.fType.rows()) {
496 // merge scalars and smaller vectors together
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500497 if (!scalarCount) {
498 this->writeType(c.fType.componentType());
499 this->write(to_string(c.fType.rows()));
500 this->write("(");
501 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500502 scalarCount += arg->fType.columns();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500503 }
504 this->writeExpression(*arg, kSequence_Precedence);
505 if (scalarCount && scalarCount == c.fType.rows()) {
506 this->write(")");
507 scalarCount = 0;
508 }
509 }
510 this->write(")");
511 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400512}
513
514void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400515 if (fRTHeightName.length()) {
516 this->write("float4(_fragCoord.x, ");
517 this->write(fRTHeightName.c_str());
518 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500519 } else {
520 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
521 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400522}
523
524void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
525 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
526 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400527 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400528 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400529 case SK_FRAGCOORD_BUILTIN:
530 this->writeFragCoord();
531 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400532 case SK_VERTEXID_BUILTIN:
533 this->write("sk_VertexID");
534 break;
535 case SK_INSTANCEID_BUILTIN:
536 this->write("sk_InstanceID");
537 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400538 case SK_CLOCKWISE_BUILTIN:
539 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
540 // clockwise to match Skia convention. This is also the default in MoltenVK.
541 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
542 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400543 default:
544 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
545 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
546 this->write("_in.");
547 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400548 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400549 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
550 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400551 this->write("_uniforms.");
552 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400553 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400554 }
555 }
Timothy Liang651286f2018-06-07 09:55:33 -0400556 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400557 }
558}
559
560void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
561 this->writeExpression(*expr.fBase, kPostfix_Precedence);
562 this->write("[");
563 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
564 this->write("]");
565}
566
567void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400568 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400569 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
570 this->writeExpression(*f.fBase, kPostfix_Precedence);
571 this->write(".");
572 }
Timothy Liang7d637782018-06-05 09:58:07 -0400573 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400574 case SK_CLIPDISTANCE_BUILTIN:
575 this->write("gl_ClipDistance");
576 break;
577 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400578 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400579 break;
580 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400581 if (field->fName == "sk_PointSize") {
582 this->write("_out->sk_PointSize");
583 } else {
584 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
585 this->write("_globals->");
586 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
587 this->write("->");
588 }
Timothy Liang651286f2018-06-07 09:55:33 -0400589 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400590 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400591 }
592}
593
594void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500595 int last = swizzle.fComponents.back();
596 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
597 this->writeType(swizzle.fType);
598 this->write("(");
599 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400600 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
601 this->write(".");
602 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500603 if (c >= 0) {
604 this->write(&("x\0y\0z\0w\0"[c * 2]));
605 }
606 }
607 if (last == SKSL_SWIZZLE_0) {
608 this->write(", 0)");
609 }
610 else if (last == SKSL_SWIZZLE_1) {
611 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400612 }
613}
614
615MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
616 switch (op) {
617 case Token::STAR: // fall through
618 case Token::SLASH: // fall through
619 case Token::PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
620 case Token::PLUS: // fall through
621 case Token::MINUS: return MetalCodeGenerator::kAdditive_Precedence;
622 case Token::SHL: // fall through
623 case Token::SHR: return MetalCodeGenerator::kShift_Precedence;
624 case Token::LT: // fall through
625 case Token::GT: // fall through
626 case Token::LTEQ: // fall through
627 case Token::GTEQ: return MetalCodeGenerator::kRelational_Precedence;
628 case Token::EQEQ: // fall through
629 case Token::NEQ: return MetalCodeGenerator::kEquality_Precedence;
630 case Token::BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
631 case Token::BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
632 case Token::BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
633 case Token::LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
634 case Token::LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
635 case Token::LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
636 case Token::EQ: // fall through
637 case Token::PLUSEQ: // fall through
638 case Token::MINUSEQ: // fall through
639 case Token::STAREQ: // fall through
640 case Token::SLASHEQ: // fall through
641 case Token::PERCENTEQ: // fall through
642 case Token::SHLEQ: // fall through
643 case Token::SHREQ: // fall through
644 case Token::LOGICALANDEQ: // fall through
645 case Token::LOGICALXOREQ: // fall through
646 case Token::LOGICALOREQ: // fall through
647 case Token::BITWISEANDEQ: // fall through
648 case Token::BITWISEXOREQ: // fall through
649 case Token::BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
650 case Token::COMMA: return MetalCodeGenerator::kSequence_Precedence;
651 default: ABORT("unsupported binary operator");
652 }
653}
654
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500655void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
656 const Type& result) {
657 String key = "TimesEqual" + left.name() + right.name();
658 if (fHelpers.find(key) == fHelpers.end()) {
659 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
660 " left = left * right;\n"
661 " return left;\n"
662 "}", result.name().c_str(), left.name().c_str(),
663 right.name().c_str());
664 }
665}
666
Ethan Nicholascc305772017-10-13 16:17:45 -0400667void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
668 Precedence parentPrecedence) {
669 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500670 bool needParens = precedence >= parentPrecedence;
671 switch (b.fOperator) {
672 case Token::EQEQ:
673 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
674 this->write("all");
675 needParens = true;
676 }
677 break;
678 case Token::NEQ:
679 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400680 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500681 needParens = true;
682 }
683 break;
684 default:
685 break;
686 }
687 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400688 this->write("(");
689 }
690 if (Compiler::IsAssignment(b.fOperator) &&
691 Expression::kVariableReference_Kind == b.fLeft->fKind &&
692 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
693 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
694 // writing to an out parameter. Since we have to turn those into pointers, we have to
695 // dereference it here.
696 this->write("*");
697 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500698 if (b.fOperator == Token::STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
699 b.fRight->fType.kind() == Type::kMatrix_Kind) {
700 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
701 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400702 this->writeExpression(*b.fLeft, precedence);
703 if (b.fOperator != Token::EQ && Compiler::IsAssignment(b.fOperator) &&
704 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
705 // This doesn't compile in Metal:
706 // float4 x = float4(1);
707 // x.xy *= float2x2(...);
708 // with the error message "non-const reference cannot bind to vector element",
709 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
710 // as long as the LHS has no side effects, and hope for the best otherwise.
711 this->write(" = ");
712 this->writeExpression(*b.fLeft, kAssignment_Precedence);
713 this->write(" ");
714 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400715 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400716 this->write(op.substr(0, op.size() - 1).c_str());
717 this->write(" ");
718 } else {
719 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
720 }
721 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500722 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400723 this->write(")");
724 }
725}
726
727void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
728 Precedence parentPrecedence) {
729 if (kTernary_Precedence >= parentPrecedence) {
730 this->write("(");
731 }
732 this->writeExpression(*t.fTest, kTernary_Precedence);
733 this->write(" ? ");
734 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
735 this->write(" : ");
736 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
737 if (kTernary_Precedence >= parentPrecedence) {
738 this->write(")");
739 }
740}
741
742void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
743 Precedence parentPrecedence) {
744 if (kPrefix_Precedence >= parentPrecedence) {
745 this->write("(");
746 }
747 this->write(Compiler::OperatorName(p.fOperator));
748 this->writeExpression(*p.fOperand, kPrefix_Precedence);
749 if (kPrefix_Precedence >= parentPrecedence) {
750 this->write(")");
751 }
752}
753
754void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
755 Precedence parentPrecedence) {
756 if (kPostfix_Precedence >= parentPrecedence) {
757 this->write("(");
758 }
759 this->writeExpression(*p.fOperand, kPostfix_Precedence);
760 this->write(Compiler::OperatorName(p.fOperator));
761 if (kPostfix_Precedence >= parentPrecedence) {
762 this->write(")");
763 }
764}
765
766void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
767 this->write(b.fValue ? "true" : "false");
768}
769
770void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
771 if (i.fType == *fContext.fUInt_Type) {
772 this->write(to_string(i.fValue & 0xffffffff) + "u");
773 } else {
774 this->write(to_string((int32_t) i.fValue));
775 }
776}
777
778void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
779 this->write(to_string(f.fValue));
780}
781
782void MetalCodeGenerator::writeSetting(const Setting& s) {
783 ABORT("internal error; setting was not folded to a constant during compilation\n");
784}
785
786void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400787 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400788 const char* separator = "";
789 if ("main" == f.fDeclaration.fName) {
790 switch (fProgram.fKind) {
791 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400792#ifdef SK_MOLTENVK
793 this->write("fragment Outputs main0");
794#else
795 this->write("fragment Outputs fragmentMain");
796#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400797 break;
798 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400799#ifdef SK_MOLTENVK
Timothy Lianga06f2152018-05-24 15:33:31 -0400800 this->write("vertex Outputs main0");
Timothy Liangb8eeb802018-07-23 16:46:16 -0400801#else
802 this->write("vertex Outputs vertexMain");
803#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400804 break;
805 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400806 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400807 }
808 this->write("(Inputs _in [[stage_in]]");
809 if (-1 != fUniformBuffer) {
810 this->write(", constant Uniforms& _uniforms [[buffer(" +
811 to_string(fUniformBuffer) + ")]]");
812 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400813 for (const auto& e : fProgram) {
814 if (ProgramElement::kVar_Kind == e.fKind) {
815 VarDeclarations& decls = (VarDeclarations&) e;
816 if (!decls.fVars.size()) {
817 continue;
818 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400819 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400820 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400821 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
Timothy Liang7d637782018-06-05 09:58:07 -0400822 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400823 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400824 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400825 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
826 this->write(")]]");
827 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400828 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400829 this->write(SAMPLER_SUFFIX);
830 this->write("[[sampler(");
831 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400832 this->write(")]]");
833 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400834 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400835 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
836 InterfaceBlock& intf = (InterfaceBlock&) e;
837 if ("sk_PerVertex" == intf.fTypeName) {
838 continue;
839 }
840 this->write(", constant ");
841 this->writeType(intf.fVariable.fType);
842 this->write("& " );
843 this->write(fInterfaceBlockNameMap[&intf]);
844 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400845#ifdef SK_MOLTENVK
Timothy Liang7d637782018-06-05 09:58:07 -0400846 this->write(to_string(intf.fVariable.fModifiers.fLayout.fSet));
Timothy Liang057c3902018-08-08 10:48:45 -0400847#else
848 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
849#endif
Timothy Lianga06f2152018-05-24 15:33:31 -0400850 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400851 }
852 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500853 if (fProgram.fKind == Program::kFragment_Kind) {
854 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400855#ifdef SK_MOLTENVK
856 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(0)]]");
857#else
858 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
859#endif
Ethan Nicholasf931e402019-07-26 15:40:33 -0400860 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400861 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400862 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400863 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400864 } else if (fProgram.fKind == Program::kVertex_Kind) {
865 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400866 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400867 separator = ", ";
868 } else {
869 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400870 this->write(" ");
871 this->writeName(f.fDeclaration.fName);
872 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400873 Requirements requirements = this->requirements(f.fDeclaration);
874 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400875 this->write("Inputs _in");
876 separator = ", ";
877 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400878 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400879 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400880 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400881 separator = ", ";
882 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400883 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400884 this->write(separator);
885 this->write("Uniforms _uniforms");
886 separator = ", ";
887 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400888 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400889 this->write(separator);
890 this->write("thread Globals* _globals");
891 separator = ", ";
892 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400893 if (requirements & kFragCoord_Requirement) {
894 this->write(separator);
895 this->write("float4 _fragCoord");
896 separator = ", ";
897 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400898 }
899 for (const auto& param : f.fDeclaration.fParameters) {
900 this->write(separator);
901 separator = ", ";
902 this->writeModifiers(param->fModifiers, false);
903 std::vector<int> sizes;
904 const Type* type = &param->fType;
905 while (Type::kArray_Kind == type->kind()) {
906 sizes.push_back(type->columns());
907 type = &type->componentType();
908 }
909 this->writeType(*type);
910 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
911 this->write("*");
912 }
Timothy Liang651286f2018-06-07 09:55:33 -0400913 this->write(" ");
914 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400915 for (int s : sizes) {
916 if (s <= 0) {
917 this->write("[]");
918 } else {
919 this->write("[" + to_string(s) + "]");
920 }
921 }
922 }
923 this->writeLine(") {");
924
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400925 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -0400926
Ethan Nicholascc305772017-10-13 16:17:45 -0400927 if ("main" == f.fDeclaration.fName) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400928 if (fNeedsGlobalStructInit) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500929 this->writeLine(" Globals globalStruct{");
930 const char* separator = "";
Timothy Liang7d637782018-06-05 09:58:07 -0400931 for (const auto& intf: fInterfaceBlockNameMap) {
932 const auto& intfName = intf.second;
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500933 this->write(separator);
934 separator = ", ";
935 this->write("&");
Timothy Liang651286f2018-06-07 09:55:33 -0400936 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400937 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400938 for (const auto& var: fInitNonConstGlobalVars) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500939 this->write(separator);
940 separator = ", ";
Timothy Liangee84fe12018-05-18 14:38:19 -0400941 this->writeVarInitializer(*var->fVar, *var->fValue);
Timothy Liangee84fe12018-05-18 14:38:19 -0400942 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400943 for (const auto& texture: fTextures) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500944 this->write(separator);
945 separator = ", ";
Timothy Liang651286f2018-06-07 09:55:33 -0400946 this->writeName(texture->fName);
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500947 this->write(separator);
Timothy Liang651286f2018-06-07 09:55:33 -0400948 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400949 this->write(SAMPLER_SUFFIX);
Timothy Liangee84fe12018-05-18 14:38:19 -0400950 }
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500951 this->writeLine("};");
952 this->writeLine(" thread Globals* _globals = &globalStruct;");
953 this->writeLine(" (void)_globals;");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400954 }
Timothy Liang7d637782018-06-05 09:58:07 -0400955 this->writeLine(" Outputs _outputStruct;");
956 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400957 }
958 fFunctionHeader = "";
959 OutputStream* oldOut = fOut;
960 StringStream buffer;
961 fOut = &buffer;
962 fIndentation++;
963 this->writeStatements(((Block&) *f.fBody).fStatements);
964 if ("main" == f.fDeclaration.fName) {
965 switch (fProgram.fKind) {
966 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -0400967 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400968 break;
969 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400970 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -0400971 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -0400972 break;
973 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400974 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400975 }
976 }
977 fIndentation--;
978 this->writeLine("}");
979
980 fOut = oldOut;
981 this->write(fFunctionHeader);
982 this->write(buffer.str());
983}
984
985void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
986 bool globalContext) {
987 if (modifiers.fFlags & Modifiers::kOut_Flag) {
988 this->write("thread ");
989 }
990 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400991 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400992 }
993}
994
995void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
996 if ("sk_PerVertex" == intf.fTypeName) {
997 return;
998 }
999 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001000 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001001 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001002 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001003 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -04001004 while (Type::kArray_Kind == structType->kind()) {
1005 structType = &structType->componentType();
1006 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001007 fIndentation++;
1008 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001009 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001010 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001011 }
1012 fIndentation--;
1013 this->write("}");
1014 if (intf.fInstanceName.size()) {
1015 this->write(" ");
1016 this->write(intf.fInstanceName);
1017 for (const auto& size : intf.fSizes) {
1018 this->write("[");
1019 if (size) {
1020 this->writeExpression(*size, kTopLevel_Precedence);
1021 }
1022 this->write("]");
1023 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001024 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1025 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001026 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001027 }
1028 this->writeLine(";");
1029}
1030
Timothy Liangdc89f192018-06-13 09:20:31 -04001031void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1032 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001033#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001034 MemoryLayout memoryLayout(MemoryLayout::k140_Standard);
Timothy Liang609fbe32018-08-10 16:40:49 -04001035#else
1036 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
1037#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001038 int currentOffset = 0;
1039 for (const auto& field: fields) {
1040 int fieldOffset = field.fModifiers.fLayout.fOffset;
1041 const Type* fieldType = field.fType;
1042 if (fieldOffset != -1) {
1043 if (currentOffset > fieldOffset) {
1044 fErrors.error(parentOffset,
1045 "offset of field '" + field.fName + "' must be at least " +
1046 to_string((int) currentOffset));
1047 } else if (currentOffset < fieldOffset) {
1048 this->write("char pad");
1049 this->write(to_string(fPaddingCount++));
1050 this->write("[");
1051 this->write(to_string(fieldOffset - currentOffset));
1052 this->writeLine("];");
1053 currentOffset = fieldOffset;
1054 }
1055 int alignment = memoryLayout.alignment(*fieldType);
1056 if (fieldOffset % alignment) {
1057 fErrors.error(parentOffset,
1058 "offset of field '" + field.fName + "' must be a multiple of " +
1059 to_string((int) alignment));
1060 }
1061 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001062#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001063 if (fieldType->kind() == Type::kVector_Kind &&
1064 fieldType->columns() == 3) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001065 SkASSERT(memoryLayout.size(*fieldType) == 3);
Timothy Liangdc89f192018-06-13 09:20:31 -04001066 // Pack all vec3 types so that their size in bytes will match what was expected in the
1067 // original SkSL code since MSL has vec3 sizes equal to 4 * component type, while SkSL
1068 // has vec3 equal to 3 * component type.
Timothy Liang609fbe32018-08-10 16:40:49 -04001069
1070 // FIXME - Packed vectors can't be accessed by swizzles, but can be indexed into. A
1071 // combination of this being a problem which only occurs when using MoltenVK and the
1072 // fact that we haven't swizzled a vec3 yet means that this problem hasn't been
1073 // addressed.
Timothy Liangdc89f192018-06-13 09:20:31 -04001074 this->write(PACKED_PREFIX);
1075 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001076#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001077 currentOffset += memoryLayout.size(*fieldType);
1078 std::vector<int> sizes;
1079 while (fieldType->kind() == Type::kArray_Kind) {
1080 sizes.push_back(fieldType->columns());
1081 fieldType = &fieldType->componentType();
1082 }
1083 this->writeModifiers(field.fModifiers, false);
1084 this->writeType(*fieldType);
1085 this->write(" ");
1086 this->writeName(field.fName);
1087 for (int s : sizes) {
1088 if (s <= 0) {
1089 this->write("[]");
1090 } else {
1091 this->write("[" + to_string(s) + "]");
1092 }
1093 }
1094 this->writeLine(";");
1095 if (parentIntf) {
1096 fInterfaceBlockMap[&field] = parentIntf;
1097 }
1098 }
1099}
1100
Ethan Nicholascc305772017-10-13 16:17:45 -04001101void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1102 this->writeExpression(value, kTopLevel_Precedence);
1103}
1104
Timothy Liang651286f2018-06-07 09:55:33 -04001105void MetalCodeGenerator::writeName(const String& name) {
1106 if (fReservedWords.find(name) != fReservedWords.end()) {
1107 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1108 }
1109 this->write(name);
1110}
1111
Ethan Nicholascc305772017-10-13 16:17:45 -04001112void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001113 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001114 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001115 for (const auto& stmt : decl.fVars) {
1116 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001117 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001118 continue;
1119 }
1120 if (wroteType) {
1121 this->write(", ");
1122 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001123 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001124 this->writeType(decl.fBaseType);
1125 this->write(" ");
1126 wroteType = true;
1127 }
Timothy Liang651286f2018-06-07 09:55:33 -04001128 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001129 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001130 this->write("[");
1131 if (size) {
1132 this->writeExpression(*size, kTopLevel_Precedence);
1133 }
1134 this->write("]");
1135 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001136 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001137 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001138 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001139 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001140 }
1141 if (wroteType) {
1142 this->write(";");
1143 }
1144}
1145
1146void MetalCodeGenerator::writeStatement(const Statement& s) {
1147 switch (s.fKind) {
1148 case Statement::kBlock_Kind:
1149 this->writeBlock((Block&) s);
1150 break;
1151 case Statement::kExpression_Kind:
1152 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1153 this->write(";");
1154 break;
1155 case Statement::kReturn_Kind:
1156 this->writeReturnStatement((ReturnStatement&) s);
1157 break;
1158 case Statement::kVarDeclarations_Kind:
1159 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1160 break;
1161 case Statement::kIf_Kind:
1162 this->writeIfStatement((IfStatement&) s);
1163 break;
1164 case Statement::kFor_Kind:
1165 this->writeForStatement((ForStatement&) s);
1166 break;
1167 case Statement::kWhile_Kind:
1168 this->writeWhileStatement((WhileStatement&) s);
1169 break;
1170 case Statement::kDo_Kind:
1171 this->writeDoStatement((DoStatement&) s);
1172 break;
1173 case Statement::kSwitch_Kind:
1174 this->writeSwitchStatement((SwitchStatement&) s);
1175 break;
1176 case Statement::kBreak_Kind:
1177 this->write("break;");
1178 break;
1179 case Statement::kContinue_Kind:
1180 this->write("continue;");
1181 break;
1182 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001183 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001184 break;
1185 case Statement::kNop_Kind:
1186 this->write(";");
1187 break;
1188 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001189#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001190 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001191#endif
1192 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001193 }
1194}
1195
1196void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1197 for (const auto& s : statements) {
1198 if (!s->isEmpty()) {
1199 this->writeStatement(*s);
1200 this->writeLine();
1201 }
1202 }
1203}
1204
1205void MetalCodeGenerator::writeBlock(const Block& b) {
1206 this->writeLine("{");
1207 fIndentation++;
1208 this->writeStatements(b.fStatements);
1209 fIndentation--;
1210 this->write("}");
1211}
1212
1213void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1214 this->write("if (");
1215 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1216 this->write(") ");
1217 this->writeStatement(*stmt.fIfTrue);
1218 if (stmt.fIfFalse) {
1219 this->write(" else ");
1220 this->writeStatement(*stmt.fIfFalse);
1221 }
1222}
1223
1224void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1225 this->write("for (");
1226 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1227 this->writeStatement(*f.fInitializer);
1228 } else {
1229 this->write("; ");
1230 }
1231 if (f.fTest) {
1232 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1233 }
1234 this->write("; ");
1235 if (f.fNext) {
1236 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1237 }
1238 this->write(") ");
1239 this->writeStatement(*f.fStatement);
1240}
1241
1242void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1243 this->write("while (");
1244 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1245 this->write(") ");
1246 this->writeStatement(*w.fStatement);
1247}
1248
1249void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1250 this->write("do ");
1251 this->writeStatement(*d.fStatement);
1252 this->write(" while (");
1253 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1254 this->write(");");
1255}
1256
1257void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1258 this->write("switch (");
1259 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1260 this->writeLine(") {");
1261 fIndentation++;
1262 for (const auto& c : s.fCases) {
1263 if (c->fValue) {
1264 this->write("case ");
1265 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1266 this->writeLine(":");
1267 } else {
1268 this->writeLine("default:");
1269 }
1270 fIndentation++;
1271 for (const auto& stmt : c->fStatements) {
1272 this->writeStatement(*stmt);
1273 this->writeLine();
1274 }
1275 fIndentation--;
1276 }
1277 fIndentation--;
1278 this->write("}");
1279}
1280
1281void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1282 this->write("return");
1283 if (r.fExpression) {
1284 this->write(" ");
1285 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1286 }
1287 this->write(";");
1288}
1289
1290void MetalCodeGenerator::writeHeader() {
1291 this->write("#include <metal_stdlib>\n");
1292 this->write("#include <simd/simd.h>\n");
1293 this->write("using namespace metal;\n");
1294}
1295
1296void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001297 for (const auto& e : fProgram) {
1298 if (ProgramElement::kVar_Kind == e.fKind) {
1299 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001300 if (!decls.fVars.size()) {
1301 continue;
1302 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001303 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001304 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1305 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001306 if (-1 == fUniformBuffer) {
1307 this->write("struct Uniforms {\n");
1308 fUniformBuffer = first.fModifiers.fLayout.fSet;
1309 if (-1 == fUniformBuffer) {
1310 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1311 }
1312 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1313 if (-1 == fUniformBuffer) {
1314 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1315 "the same 'layout(set=...)'");
1316 }
1317 }
1318 this->write(" ");
1319 this->writeType(first.fType);
1320 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001321 for (const auto& stmt : decls.fVars) {
1322 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001323 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001324 }
1325 this->write(";\n");
1326 }
1327 }
1328 }
1329 if (-1 != fUniformBuffer) {
1330 this->write("};\n");
1331 }
1332}
1333
1334void MetalCodeGenerator::writeInputStruct() {
1335 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001336 for (const auto& e : fProgram) {
1337 if (ProgramElement::kVar_Kind == e.fKind) {
1338 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001339 if (!decls.fVars.size()) {
1340 continue;
1341 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001342 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001343 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1344 -1 == first.fModifiers.fLayout.fBuiltin) {
1345 this->write(" ");
1346 this->writeType(first.fType);
1347 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001348 for (const auto& stmt : decls.fVars) {
1349 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001350 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001351 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001352 if (fProgram.fKind == Program::kVertex_Kind) {
1353 this->write(" [[attribute(" +
1354 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1355 } else if (fProgram.fKind == Program::kFragment_Kind) {
1356 this->write(" [[user(locn" +
1357 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1358 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001359 }
1360 }
1361 this->write(";\n");
1362 }
1363 }
1364 }
1365 this->write("};\n");
1366}
1367
1368void MetalCodeGenerator::writeOutputStruct() {
1369 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001370 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001371 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001372 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001373 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001374 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001375 for (const auto& e : fProgram) {
1376 if (ProgramElement::kVar_Kind == e.fKind) {
1377 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001378 if (!decls.fVars.size()) {
1379 continue;
1380 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001381 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001382 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1383 -1 == first.fModifiers.fLayout.fBuiltin) {
1384 this->write(" ");
1385 this->writeType(first.fType);
1386 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001387 for (const auto& stmt : decls.fVars) {
1388 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001389 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001390 if (fProgram.fKind == Program::kVertex_Kind) {
1391 this->write(" [[user(locn" +
1392 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1393 } else if (fProgram.fKind == Program::kFragment_Kind) {
1394 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001395 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1396 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1397 if (colorIndex) {
1398 this->write(", index(" + to_string(colorIndex) + ")");
1399 }
1400 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001401 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001402 }
1403 this->write(";\n");
1404 }
1405 }
Timothy Liang7d637782018-06-05 09:58:07 -04001406 }
1407 if (fProgram.fKind == Program::kVertex_Kind) {
1408 this->write(" float sk_PointSize;\n");
1409 }
1410 this->write("};\n");
1411}
1412
1413void MetalCodeGenerator::writeInterfaceBlocks() {
1414 bool wroteInterfaceBlock = false;
1415 for (const auto& e : fProgram) {
1416 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1417 this->writeInterfaceBlock((InterfaceBlock&) e);
1418 wroteInterfaceBlock = true;
1419 }
1420 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001421 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001422 this->writeLine("struct sksl_synthetic_uniforms {");
1423 this->writeLine(" float u_skRTHeight;");
1424 this->writeLine("};");
1425 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001426}
1427
Timothy Liangee84fe12018-05-18 14:38:19 -04001428void MetalCodeGenerator::writeGlobalStruct() {
1429 bool wroteStructDecl = false;
Timothy Liang7d637782018-06-05 09:58:07 -04001430 for (const auto& intf : fInterfaceBlockNameMap) {
1431 if (!wroteStructDecl) {
1432 this->write("struct Globals {\n");
1433 wroteStructDecl = true;
1434 }
1435 fNeedsGlobalStructInit = true;
1436 const auto& intfType = intf.first;
1437 const auto& intfName = intf.second;
1438 this->write(" constant ");
1439 this->write(intfType->fTypeName);
1440 this->write("* ");
Timothy Liang651286f2018-06-07 09:55:33 -04001441 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -04001442 this->write(";\n");
1443 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001444 for (const auto& e : fProgram) {
1445 if (ProgramElement::kVar_Kind == e.fKind) {
1446 VarDeclarations& decls = (VarDeclarations&) e;
1447 if (!decls.fVars.size()) {
1448 continue;
1449 }
1450 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001451 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1452 first.fType.kind() == Type::kSampler_Kind) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001453 if (!wroteStructDecl) {
1454 this->write("struct Globals {\n");
1455 wroteStructDecl = true;
1456 }
1457 fNeedsGlobalStructInit = true;
1458 this->write(" ");
1459 this->writeType(first.fType);
1460 this->write(" ");
1461 for (const auto& stmt : decls.fVars) {
1462 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001463 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001464 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1465 fTextures.push_back(var.fVar);
1466 this->write(";\n");
1467 this->write(" sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -04001468 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001469 this->write(SAMPLER_SUFFIX);
1470 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001471 if (var.fValue) {
1472 fInitNonConstGlobalVars.push_back(&var);
1473 }
1474 }
1475 this->write(";\n");
1476 }
1477 }
1478 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001479 if (wroteStructDecl) {
1480 this->write("};\n");
1481 }
1482}
1483
Ethan Nicholascc305772017-10-13 16:17:45 -04001484void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1485 switch (e.fKind) {
1486 case ProgramElement::kExtension_Kind:
1487 break;
1488 case ProgramElement::kVar_Kind: {
1489 VarDeclarations& decl = (VarDeclarations&) e;
1490 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001491 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001492 if (-1 == builtin) {
1493 // normal var
1494 this->writeVarDeclarations(decl, true);
1495 this->writeLine();
1496 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1497 // ignore
1498 }
1499 }
1500 break;
1501 }
1502 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001503 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001504 break;
1505 case ProgramElement::kFunction_Kind:
1506 this->writeFunction((FunctionDefinition&) e);
1507 break;
1508 case ProgramElement::kModifiers_Kind:
1509 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1510 this->writeLine(";");
1511 break;
1512 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001513#ifdef SK_DEBUG
1514 ABORT("unsupported program element: %s\n", e.description().c_str());
1515#endif
1516 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001517 }
1518}
1519
1520MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression& e) {
1521 switch (e.fKind) {
1522 case Expression::kFunctionCall_Kind: {
1523 const FunctionCall& f = (const FunctionCall&) e;
1524 Requirements result = this->requirements(f.fFunction);
1525 for (const auto& e : f.fArguments) {
1526 result |= this->requirements(*e);
1527 }
1528 return result;
1529 }
1530 case Expression::kConstructor_Kind: {
1531 const Constructor& c = (const Constructor&) e;
1532 Requirements result = kNo_Requirements;
1533 for (const auto& e : c.fArguments) {
1534 result |= this->requirements(*e);
1535 }
1536 return result;
1537 }
Timothy Liang7d637782018-06-05 09:58:07 -04001538 case Expression::kFieldAccess_Kind: {
1539 const FieldAccess& f = (const FieldAccess&) e;
1540 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1541 return kGlobals_Requirement;
1542 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001543 return this->requirements(*((const FieldAccess&) e).fBase);
Timothy Liang7d637782018-06-05 09:58:07 -04001544 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001545 case Expression::kSwizzle_Kind:
1546 return this->requirements(*((const Swizzle&) e).fBase);
1547 case Expression::kBinary_Kind: {
1548 const BinaryExpression& b = (const BinaryExpression&) e;
1549 return this->requirements(*b.fLeft) | this->requirements(*b.fRight);
1550 }
1551 case Expression::kIndex_Kind: {
1552 const IndexExpression& idx = (const IndexExpression&) e;
1553 return this->requirements(*idx.fBase) | this->requirements(*idx.fIndex);
1554 }
1555 case Expression::kPrefix_Kind:
1556 return this->requirements(*((const PrefixExpression&) e).fOperand);
1557 case Expression::kPostfix_Kind:
1558 return this->requirements(*((const PostfixExpression&) e).fOperand);
1559 case Expression::kTernary_Kind: {
1560 const TernaryExpression& t = (const TernaryExpression&) e;
1561 return this->requirements(*t.fTest) | this->requirements(*t.fIfTrue) |
1562 this->requirements(*t.fIfFalse);
1563 }
1564 case Expression::kVariableReference_Kind: {
1565 const VariableReference& v = (const VariableReference&) e;
1566 Requirements result = kNo_Requirements;
1567 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001568 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001569 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1570 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1571 result = kInputs_Requirement;
1572 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1573 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001574 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1575 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001576 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001577 } else {
1578 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001579 }
1580 }
1581 return result;
1582 }
1583 default:
1584 return kNo_Requirements;
1585 }
1586}
1587
1588MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement& s) {
1589 switch (s.fKind) {
1590 case Statement::kBlock_Kind: {
1591 Requirements result = kNo_Requirements;
1592 for (const auto& child : ((const Block&) s).fStatements) {
1593 result |= this->requirements(*child);
1594 }
1595 return result;
1596 }
Timothy Liang7d637782018-06-05 09:58:07 -04001597 case Statement::kVarDeclaration_Kind: {
1598 Requirements result = kNo_Requirements;
1599 const VarDeclaration& var = (const VarDeclaration&) s;
1600 if (var.fValue) {
1601 result = this->requirements(*var.fValue);
1602 }
1603 return result;
1604 }
1605 case Statement::kVarDeclarations_Kind: {
1606 Requirements result = kNo_Requirements;
1607 const VarDeclarations& decls = *((const VarDeclarationsStatement&) s).fDeclaration;
1608 for (const auto& stmt : decls.fVars) {
1609 result |= this->requirements(*stmt);
1610 }
1611 return result;
1612 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001613 case Statement::kExpression_Kind:
1614 return this->requirements(*((const ExpressionStatement&) s).fExpression);
1615 case Statement::kReturn_Kind: {
1616 const ReturnStatement& r = (const ReturnStatement&) s;
1617 if (r.fExpression) {
1618 return this->requirements(*r.fExpression);
1619 }
1620 return kNo_Requirements;
1621 }
1622 case Statement::kIf_Kind: {
1623 const IfStatement& i = (const IfStatement&) s;
1624 return this->requirements(*i.fTest) |
1625 this->requirements(*i.fIfTrue) |
Ethan Nicholasf931e402019-07-26 15:40:33 -04001626 (i.fIfFalse ? this->requirements(*i.fIfFalse) : 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001627 }
1628 case Statement::kFor_Kind: {
1629 const ForStatement& f = (const ForStatement&) s;
1630 return this->requirements(*f.fInitializer) |
1631 this->requirements(*f.fTest) |
1632 this->requirements(*f.fNext) |
1633 this->requirements(*f.fStatement);
1634 }
1635 case Statement::kWhile_Kind: {
1636 const WhileStatement& w = (const WhileStatement&) s;
1637 return this->requirements(*w.fTest) |
1638 this->requirements(*w.fStatement);
1639 }
1640 case Statement::kDo_Kind: {
1641 const DoStatement& d = (const DoStatement&) s;
1642 return this->requirements(*d.fTest) |
1643 this->requirements(*d.fStatement);
1644 }
1645 case Statement::kSwitch_Kind: {
1646 const SwitchStatement& sw = (const SwitchStatement&) s;
1647 Requirements result = this->requirements(*sw.fValue);
1648 for (const auto& c : sw.fCases) {
1649 for (const auto& st : c->fStatements) {
1650 result |= this->requirements(*st);
1651 }
1652 }
1653 return result;
1654 }
1655 default:
1656 return kNo_Requirements;
1657 }
1658}
1659
1660MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1661 if (f.fBuiltin) {
1662 return kNo_Requirements;
1663 }
1664 auto found = fRequirements.find(&f);
1665 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001666 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001667 for (const auto& e : fProgram) {
1668 if (ProgramElement::kFunction_Kind == e.fKind) {
1669 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001670 if (&def.fDeclaration == &f) {
1671 Requirements reqs = this->requirements(*def.fBody);
1672 fRequirements[&f] = reqs;
1673 return reqs;
1674 }
1675 }
1676 }
1677 }
1678 return found->second;
1679}
1680
Timothy Liangb8eeb802018-07-23 16:46:16 -04001681bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001682 OutputStream* rawOut = fOut;
1683 fOut = &fHeader;
Timothy Liangb8eeb802018-07-23 16:46:16 -04001684#ifdef SK_MOLTENVK
1685 fOut->write((const char*) &MVKMagicNum, sizeof(MVKMagicNum));
1686#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001687 fProgramKind = fProgram.fKind;
1688 this->writeHeader();
1689 this->writeUniformStruct();
1690 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001691 this->writeOutputStruct();
1692 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001693 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001694 StringStream body;
1695 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001696 for (const auto& e : fProgram) {
1697 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001698 }
1699 fOut = rawOut;
1700
1701 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001702 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001703 write_stringstream(body, *rawOut);
Timothy Liangb8eeb802018-07-23 16:46:16 -04001704#ifdef SK_MOLTENVK
1705 this->write("\0");
1706#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001707 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001708}
1709
1710}