blob: 66f73dfecd5cde7ce105f7d34bb555e51bcb9521 [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 Nicholas5a9a9b82019-09-20 12:59:22 -040072void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholascc305772017-10-13 16:17:45 -040073 switch (type.kind()) {
74 case Type::kStruct_Kind:
Ethan Nicholas5a9a9b82019-09-20 12:59:22 -040075 for (const Type* search : fWrittenStructs) {
76 if (*search == type) {
77 // already written
78 this->write(type.name());
79 return;
80 }
81 }
82 fWrittenStructs.push_back(&type);
83 this->writeLine("struct " + type.name() + " {");
84 fIndentation++;
85 this->writeFields(type.fields(), type.fOffset);
86 fIndentation--;
87 this->write("}");
88 break;
Ethan Nicholascc305772017-10-13 16:17:45 -040089 case Type::kVector_Kind:
Ethan Nicholas5a9a9b82019-09-20 12:59:22 -040090 this->writeType(type.componentType());
91 this->write(to_string(type.columns()));
92 break;
Timothy Liang43d225f2018-07-19 15:27:13 -040093 case Type::kMatrix_Kind:
Ethan Nicholas5a9a9b82019-09-20 12:59:22 -040094 this->writeType(type.componentType());
95 this->write(to_string(type.columns()));
96 this->write("x");
97 this->write(to_string(type.rows()));
98 break;
Timothy Liangee84fe12018-05-18 14:38:19 -040099 case Type::kSampler_Kind:
Ethan Nicholas5a9a9b82019-09-20 12:59:22 -0400100 this->write("texture2d<float> "); // FIXME - support other texture types;
101 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400102 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400103 if (type == *fContext.fHalf_Type) {
104 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas5a9a9b82019-09-20 12:59:22 -0400105 this->write(fContext.fFloat_Type->name());
Timothy Liang43d225f2018-07-19 15:27:13 -0400106 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas5a9a9b82019-09-20 12:59:22 -0400107 this->write("char");
Timothy Liang43d225f2018-07-19 15:27:13 -0400108 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas5a9a9b82019-09-20 12:59:22 -0400109 this->write("uchar");
Timothy Liang7d637782018-06-05 09:58:07 -0400110 } else {
Ethan Nicholas5a9a9b82019-09-20 12:59:22 -0400111 this->write(type.name());
Timothy Liang7d637782018-06-05 09:58:07 -0400112 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400113 }
114}
115
116void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
117 switch (expr.fKind) {
118 case Expression::kBinary_Kind:
119 this->writeBinaryExpression((BinaryExpression&) expr, parentPrecedence);
120 break;
121 case Expression::kBoolLiteral_Kind:
122 this->writeBoolLiteral((BoolLiteral&) expr);
123 break;
124 case Expression::kConstructor_Kind:
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500125 this->writeConstructor((Constructor&) expr, parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
127 case Expression::kIntLiteral_Kind:
128 this->writeIntLiteral((IntLiteral&) expr);
129 break;
130 case Expression::kFieldAccess_Kind:
131 this->writeFieldAccess(((FieldAccess&) expr));
132 break;
133 case Expression::kFloatLiteral_Kind:
134 this->writeFloatLiteral(((FloatLiteral&) expr));
135 break;
136 case Expression::kFunctionCall_Kind:
137 this->writeFunctionCall((FunctionCall&) expr);
138 break;
139 case Expression::kPrefix_Kind:
140 this->writePrefixExpression((PrefixExpression&) expr, parentPrecedence);
141 break;
142 case Expression::kPostfix_Kind:
143 this->writePostfixExpression((PostfixExpression&) expr, parentPrecedence);
144 break;
145 case Expression::kSetting_Kind:
146 this->writeSetting((Setting&) expr);
147 break;
148 case Expression::kSwizzle_Kind:
149 this->writeSwizzle((Swizzle&) expr);
150 break;
151 case Expression::kVariableReference_Kind:
152 this->writeVariableReference((VariableReference&) expr);
153 break;
154 case Expression::kTernary_Kind:
155 this->writeTernaryExpression((TernaryExpression&) expr, parentPrecedence);
156 break;
157 case Expression::kIndex_Kind:
158 this->writeIndexExpression((IndexExpression&) expr);
159 break;
160 default:
161 ABORT("unsupported expression: %s", expr.description().c_str());
162 }
163}
164
Timothy Liang6403b0e2018-05-17 10:40:04 -0400165void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400166 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400167 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400168 Intrinsic intrinsic = i->second;
169 int32_t intrinsicId = intrinsic.second;
170 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400171 case kSpecial_IntrinsicKind:
172 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400173 break;
174 case kMetal_IntrinsicKind:
175 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
176 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500177 case kEqual_MetalIntrinsic:
178 this->write(" == ");
179 break;
180 case kNotEqual_MetalIntrinsic:
181 this->write(" != ");
182 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400183 case kLessThan_MetalIntrinsic:
184 this->write(" < ");
185 break;
186 case kLessThanEqual_MetalIntrinsic:
187 this->write(" <= ");
188 break;
189 case kGreaterThan_MetalIntrinsic:
190 this->write(" > ");
191 break;
192 case kGreaterThanEqual_MetalIntrinsic:
193 this->write(" >= ");
194 break;
195 default:
196 ABORT("unsupported metal intrinsic kind");
197 }
198 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
199 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400200 default:
201 ABORT("unsupported intrinsic kind");
202 }
203}
204
Ethan Nicholascc305772017-10-13 16:17:45 -0400205void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400206 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
207 if (entry != fIntrinsicMap.end()) {
208 this->writeIntrinsicCall(c);
209 return;
210 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400211 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
212 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400213 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
214 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500215 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
216 SkASSERT(c.fArguments.size() == 1);
217 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400218 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
219 this->write("dfdx");
220 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700221 // Flipping Y also negates the Y derivatives.
222 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400223 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400224 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400225 }
226 this->write("(");
227 const char* separator = "";
228 if (this->requirements(c.fFunction) & kInputs_Requirement) {
229 this->write("_in");
230 separator = ", ";
231 }
232 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
233 this->write(separator);
234 this->write("_out");
235 separator = ", ";
236 }
237 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
238 this->write(separator);
239 this->write("_uniforms");
240 separator = ", ";
241 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400242 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
243 this->write(separator);
244 this->write("_globals");
245 separator = ", ";
246 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400247 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
248 this->write(separator);
249 this->write("_fragCoord");
250 separator = ", ";
251 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400252 for (size_t i = 0; i < c.fArguments.size(); ++i) {
253 const Expression& arg = *c.fArguments[i];
254 this->write(separator);
255 separator = ", ";
256 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
257 this->write("&");
258 }
259 this->writeExpression(arg, kSequence_Precedence);
260 }
261 this->write(")");
262}
263
Chris Daltondba7aab2018-11-15 10:57:49 -0500264void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500265 String typeName = mat.fType.name();
266 String name = typeName + "_inverse";
267 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500268 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
269 fWrittenIntrinsics.insert(name);
270 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500271 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500272 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
273 "}"
274 ).c_str());
275 }
276 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500277 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
278 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
279 fWrittenIntrinsics.insert(name);
280 fExtraFunctions.writeText((
281 typeName + " " + name + "(" + typeName + " m) {"
282 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
283 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
284 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
285 " float b01 = a22 * a11 - a12 * a21;"
286 " float b11 = -a22 * a10 + a12 * a20;"
287 " float b21 = a21 * a10 - a11 * a20;"
288 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
289 " return " + typeName +
290 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
291 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
292 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
293 " (1/det);"
294 "}"
295 ).c_str());
296 }
297 }
298 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
299 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
300 fWrittenIntrinsics.insert(name);
301 fExtraFunctions.writeText((
302 typeName + " " + name + "(" + typeName + " m) {"
303 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
304 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
305 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
306 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
307 " float b00 = a00 * a11 - a01 * a10;"
308 " float b01 = a00 * a12 - a02 * a10;"
309 " float b02 = a00 * a13 - a03 * a10;"
310 " float b03 = a01 * a12 - a02 * a11;"
311 " float b04 = a01 * a13 - a03 * a11;"
312 " float b05 = a02 * a13 - a03 * a12;"
313 " float b06 = a20 * a31 - a21 * a30;"
314 " float b07 = a20 * a32 - a22 * a30;"
315 " float b08 = a20 * a33 - a23 * a30;"
316 " float b09 = a21 * a32 - a22 * a31;"
317 " float b10 = a21 * a33 - a23 * a31;"
318 " float b11 = a22 * a33 - a23 * a32;"
319 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
320 " b04 * b07 + b05 * b06;"
321 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
322 " a02 * b10 - a01 * b11 - a03 * b09,"
323 " a31 * b05 - a32 * b04 + a33 * b03,"
324 " a22 * b04 - a21 * b05 - a23 * b03,"
325 " a12 * b08 - a10 * b11 - a13 * b07,"
326 " a00 * b11 - a02 * b08 + a03 * b07,"
327 " a32 * b02 - a30 * b05 - a33 * b01,"
328 " a20 * b05 - a22 * b02 + a23 * b01,"
329 " a10 * b10 - a11 * b08 + a13 * b06,"
330 " a01 * b08 - a00 * b10 - a03 * b06,"
331 " a30 * b04 - a31 * b02 + a33 * b00,"
332 " a21 * b02 - a20 * b04 - a23 * b00,"
333 " a11 * b07 - a10 * b09 - a12 * b06,"
334 " a00 * b09 - a01 * b07 + a02 * b06,"
335 " a31 * b01 - a30 * b03 - a32 * b00,"
336 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
337 "}"
338 ).c_str());
339 }
340 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500341 this->write(name);
342}
343
Timothy Liang6403b0e2018-05-17 10:40:04 -0400344void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
345 switch (kind) {
346 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400347 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400348 this->write(".sample(");
349 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
350 this->write(SAMPLER_SUFFIX);
351 this->write(", ");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400352 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400353 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
354 this->write(".xy)"); // FIXME - add projection functionality
355 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400356 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Timothy Liangee84fe12018-05-18 14:38:19 -0400357 this->write(")");
358 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400359 break;
Timothy Liang651286f2018-06-07 09:55:33 -0400360 case kMod_SpecialIntrinsic:
361 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
362 this->write("((");
363 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
364 this->write(") - (");
365 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
366 this->write(") * floor((");
367 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
368 this->write(") / (");
369 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
370 this->write(")))");
371 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400372 default:
373 ABORT("unsupported special intrinsic kind");
374 }
375}
376
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500377// If it hasn't already been written, writes a constructor for 'matrix' which takes a single value
378// of type 'arg'.
379String MetalCodeGenerator::getMatrixConstructHelper(const Type& matrix, const Type& arg) {
380 String key = matrix.name() + arg.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500381 auto found = fHelpers.find(key);
382 if (found != fHelpers.end()) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500383 return found->second;
Ethan Nicholascc305772017-10-13 16:17:45 -0400384 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500385 String name;
386 int columns = matrix.columns();
387 int rows = matrix.rows();
388 if (arg.isNumber()) {
389 // creating a matrix from a single scalar value
390 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float";
391 fExtraFunctions.printf("float%dx%d %s(float x) {\n",
392 columns, rows, name.c_str());
393 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
394 for (int i = 0; i < columns; ++i) {
395 if (i > 0) {
396 fExtraFunctions.writeText(", ");
397 }
398 fExtraFunctions.printf("float%d(", rows);
399 for (int j = 0; j < rows; ++j) {
400 if (j > 0) {
401 fExtraFunctions.writeText(", ");
402 }
403 if (i == j) {
404 fExtraFunctions.writeText("x");
405 } else {
406 fExtraFunctions.writeText("0");
407 }
408 }
409 fExtraFunctions.writeText(")");
410 }
411 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500412 } else if (arg.kind() == Type::kMatrix_Kind) {
413 // creating a matrix from another matrix
414 int argColumns = arg.columns();
415 int argRows = arg.rows();
416 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float" +
417 to_string(argColumns) + "x" + to_string(argRows);
418 fExtraFunctions.printf("float%dx%d %s(float%dx%d m) {\n",
419 columns, rows, name.c_str(), argColumns, argRows);
420 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
421 for (int i = 0; i < columns; ++i) {
422 if (i > 0) {
423 fExtraFunctions.writeText(", ");
424 }
425 fExtraFunctions.printf("float%d(", rows);
426 for (int j = 0; j < rows; ++j) {
427 if (j > 0) {
428 fExtraFunctions.writeText(", ");
429 }
430 if (i < argColumns && j < argRows) {
431 fExtraFunctions.printf("m[%d][%d]", i, j);
432 } else {
433 fExtraFunctions.writeText("0");
434 }
435 }
436 fExtraFunctions.writeText(")");
437 }
438 fExtraFunctions.writeText(");\n}\n");
439 } else if (matrix.rows() == 2 && matrix.columns() == 2 && arg == *fContext.fFloat4_Type) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500440 // float2x2(float4) doesn't work, need to split it into float2x2(float2, float2)
441 name = "float2x2_from_float4";
442 fExtraFunctions.printf(
443 "float2x2 %s(float4 v) {\n"
444 " return float2x2(float2(v[0], v[1]), float2(v[2], v[3]));\n"
445 "}\n",
446 name.c_str()
447 );
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500448 } else {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500449 SkASSERT(false);
450 name = "<error>";
451 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500452 fHelpers[key] = name;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500453 return name;
454}
455
456bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
457 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
458 return false;
459 }
460 if (t1.columns() > 1) {
461 return this->canCoerce(t1.componentType(), t2.componentType());
462 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500463 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500464}
465
466void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
467 if (c.fArguments.size() == 1 && this->canCoerce(c.fType, c.fArguments[0]->fType)) {
468 this->writeExpression(*c.fArguments[0], parentPrecedence);
469 return;
470 }
471 if (c.fType.kind() == Type::kMatrix_Kind && c.fArguments.size() == 1) {
472 const Expression& arg = *c.fArguments[0];
473 String name = this->getMatrixConstructHelper(c.fType, arg.fType);
474 this->write(name);
475 this->write("(");
476 this->writeExpression(arg, kSequence_Precedence);
477 this->write(")");
478 } else {
479 this->writeType(c.fType);
480 this->write("(");
481 const char* separator = "";
482 int scalarCount = 0;
483 for (const auto& arg : c.fArguments) {
484 this->write(separator);
485 separator = ", ";
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500486 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() != c.fType.rows()) {
487 // merge scalars and smaller vectors together
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500488 if (!scalarCount) {
489 this->writeType(c.fType.componentType());
490 this->write(to_string(c.fType.rows()));
491 this->write("(");
492 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500493 scalarCount += arg->fType.columns();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500494 }
495 this->writeExpression(*arg, kSequence_Precedence);
496 if (scalarCount && scalarCount == c.fType.rows()) {
497 this->write(")");
498 scalarCount = 0;
499 }
500 }
501 this->write(")");
502 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400503}
504
505void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400506 if (fRTHeightName.length()) {
507 this->write("float4(_fragCoord.x, ");
508 this->write(fRTHeightName.c_str());
509 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500510 } else {
511 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
512 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400513}
514
515void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
516 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
517 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400518 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400519 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400520 case SK_FRAGCOORD_BUILTIN:
521 this->writeFragCoord();
522 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400523 case SK_VERTEXID_BUILTIN:
524 this->write("sk_VertexID");
525 break;
526 case SK_INSTANCEID_BUILTIN:
527 this->write("sk_InstanceID");
528 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400529 case SK_CLOCKWISE_BUILTIN:
530 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
531 // clockwise to match Skia convention. This is also the default in MoltenVK.
532 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
533 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400534 default:
535 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
536 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
537 this->write("_in.");
538 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400539 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400540 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
541 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400542 this->write("_uniforms.");
543 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400544 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400545 }
546 }
Timothy Liang651286f2018-06-07 09:55:33 -0400547 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400548 }
549}
550
551void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
552 this->writeExpression(*expr.fBase, kPostfix_Precedence);
553 this->write("[");
554 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
555 this->write("]");
556}
557
558void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400559 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400560 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
561 this->writeExpression(*f.fBase, kPostfix_Precedence);
562 this->write(".");
563 }
Timothy Liang7d637782018-06-05 09:58:07 -0400564 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400565 case SK_CLIPDISTANCE_BUILTIN:
566 this->write("gl_ClipDistance");
567 break;
568 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400569 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400570 break;
571 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400572 if (field->fName == "sk_PointSize") {
573 this->write("_out->sk_PointSize");
574 } else {
575 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
576 this->write("_globals->");
577 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
578 this->write("->");
579 }
Timothy Liang651286f2018-06-07 09:55:33 -0400580 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400581 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400582 }
583}
584
585void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500586 int last = swizzle.fComponents.back();
587 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
588 this->writeType(swizzle.fType);
589 this->write("(");
590 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400591 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
592 this->write(".");
593 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500594 if (c >= 0) {
595 this->write(&("x\0y\0z\0w\0"[c * 2]));
596 }
597 }
598 if (last == SKSL_SWIZZLE_0) {
599 this->write(", 0)");
600 }
601 else if (last == SKSL_SWIZZLE_1) {
602 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400603 }
604}
605
606MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
607 switch (op) {
608 case Token::STAR: // fall through
609 case Token::SLASH: // fall through
610 case Token::PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
611 case Token::PLUS: // fall through
612 case Token::MINUS: return MetalCodeGenerator::kAdditive_Precedence;
613 case Token::SHL: // fall through
614 case Token::SHR: return MetalCodeGenerator::kShift_Precedence;
615 case Token::LT: // fall through
616 case Token::GT: // fall through
617 case Token::LTEQ: // fall through
618 case Token::GTEQ: return MetalCodeGenerator::kRelational_Precedence;
619 case Token::EQEQ: // fall through
620 case Token::NEQ: return MetalCodeGenerator::kEquality_Precedence;
621 case Token::BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
622 case Token::BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
623 case Token::BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
624 case Token::LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
625 case Token::LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
626 case Token::LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
627 case Token::EQ: // fall through
628 case Token::PLUSEQ: // fall through
629 case Token::MINUSEQ: // fall through
630 case Token::STAREQ: // fall through
631 case Token::SLASHEQ: // fall through
632 case Token::PERCENTEQ: // fall through
633 case Token::SHLEQ: // fall through
634 case Token::SHREQ: // fall through
635 case Token::LOGICALANDEQ: // fall through
636 case Token::LOGICALXOREQ: // fall through
637 case Token::LOGICALOREQ: // fall through
638 case Token::BITWISEANDEQ: // fall through
639 case Token::BITWISEXOREQ: // fall through
640 case Token::BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
641 case Token::COMMA: return MetalCodeGenerator::kSequence_Precedence;
642 default: ABORT("unsupported binary operator");
643 }
644}
645
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500646void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
647 const Type& result) {
648 String key = "TimesEqual" + left.name() + right.name();
649 if (fHelpers.find(key) == fHelpers.end()) {
650 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
651 " left = left * right;\n"
652 " return left;\n"
653 "}", result.name().c_str(), left.name().c_str(),
654 right.name().c_str());
655 }
656}
657
Ethan Nicholascc305772017-10-13 16:17:45 -0400658void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
659 Precedence parentPrecedence) {
660 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500661 bool needParens = precedence >= parentPrecedence;
662 switch (b.fOperator) {
663 case Token::EQEQ:
664 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
665 this->write("all");
666 needParens = true;
667 }
668 break;
669 case Token::NEQ:
670 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400671 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500672 needParens = true;
673 }
674 break;
675 default:
676 break;
677 }
678 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400679 this->write("(");
680 }
681 if (Compiler::IsAssignment(b.fOperator) &&
682 Expression::kVariableReference_Kind == b.fLeft->fKind &&
683 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
684 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
685 // writing to an out parameter. Since we have to turn those into pointers, we have to
686 // dereference it here.
687 this->write("*");
688 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500689 if (b.fOperator == Token::STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
690 b.fRight->fType.kind() == Type::kMatrix_Kind) {
691 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
692 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400693 this->writeExpression(*b.fLeft, precedence);
694 if (b.fOperator != Token::EQ && Compiler::IsAssignment(b.fOperator) &&
695 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
696 // This doesn't compile in Metal:
697 // float4 x = float4(1);
698 // x.xy *= float2x2(...);
699 // with the error message "non-const reference cannot bind to vector element",
700 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
701 // as long as the LHS has no side effects, and hope for the best otherwise.
702 this->write(" = ");
703 this->writeExpression(*b.fLeft, kAssignment_Precedence);
704 this->write(" ");
705 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400706 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400707 this->write(op.substr(0, op.size() - 1).c_str());
708 this->write(" ");
709 } else {
710 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
711 }
712 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500713 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400714 this->write(")");
715 }
716}
717
718void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
719 Precedence parentPrecedence) {
720 if (kTernary_Precedence >= parentPrecedence) {
721 this->write("(");
722 }
723 this->writeExpression(*t.fTest, kTernary_Precedence);
724 this->write(" ? ");
725 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
726 this->write(" : ");
727 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
728 if (kTernary_Precedence >= parentPrecedence) {
729 this->write(")");
730 }
731}
732
733void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
734 Precedence parentPrecedence) {
735 if (kPrefix_Precedence >= parentPrecedence) {
736 this->write("(");
737 }
738 this->write(Compiler::OperatorName(p.fOperator));
739 this->writeExpression(*p.fOperand, kPrefix_Precedence);
740 if (kPrefix_Precedence >= parentPrecedence) {
741 this->write(")");
742 }
743}
744
745void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
746 Precedence parentPrecedence) {
747 if (kPostfix_Precedence >= parentPrecedence) {
748 this->write("(");
749 }
750 this->writeExpression(*p.fOperand, kPostfix_Precedence);
751 this->write(Compiler::OperatorName(p.fOperator));
752 if (kPostfix_Precedence >= parentPrecedence) {
753 this->write(")");
754 }
755}
756
757void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
758 this->write(b.fValue ? "true" : "false");
759}
760
761void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
762 if (i.fType == *fContext.fUInt_Type) {
763 this->write(to_string(i.fValue & 0xffffffff) + "u");
764 } else {
765 this->write(to_string((int32_t) i.fValue));
766 }
767}
768
769void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
770 this->write(to_string(f.fValue));
771}
772
773void MetalCodeGenerator::writeSetting(const Setting& s) {
774 ABORT("internal error; setting was not folded to a constant during compilation\n");
775}
776
777void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400778 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400779 const char* separator = "";
780 if ("main" == f.fDeclaration.fName) {
781 switch (fProgram.fKind) {
782 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400783#ifdef SK_MOLTENVK
784 this->write("fragment Outputs main0");
785#else
786 this->write("fragment Outputs fragmentMain");
787#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400788 break;
789 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400790#ifdef SK_MOLTENVK
Timothy Lianga06f2152018-05-24 15:33:31 -0400791 this->write("vertex Outputs main0");
Timothy Liangb8eeb802018-07-23 16:46:16 -0400792#else
793 this->write("vertex Outputs vertexMain");
794#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400795 break;
796 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400797 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400798 }
799 this->write("(Inputs _in [[stage_in]]");
800 if (-1 != fUniformBuffer) {
801 this->write(", constant Uniforms& _uniforms [[buffer(" +
802 to_string(fUniformBuffer) + ")]]");
803 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400804 for (const auto& e : fProgram) {
805 if (ProgramElement::kVar_Kind == e.fKind) {
806 VarDeclarations& decls = (VarDeclarations&) e;
807 if (!decls.fVars.size()) {
808 continue;
809 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400810 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400811 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400812 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
Timothy Liang7d637782018-06-05 09:58:07 -0400813 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400814 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400815 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400816 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
817 this->write(")]]");
818 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400819 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400820 this->write(SAMPLER_SUFFIX);
821 this->write("[[sampler(");
822 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400823 this->write(")]]");
824 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400825 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400826 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
827 InterfaceBlock& intf = (InterfaceBlock&) e;
828 if ("sk_PerVertex" == intf.fTypeName) {
829 continue;
830 }
831 this->write(", constant ");
832 this->writeType(intf.fVariable.fType);
833 this->write("& " );
834 this->write(fInterfaceBlockNameMap[&intf]);
835 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400836#ifdef SK_MOLTENVK
Timothy Liang7d637782018-06-05 09:58:07 -0400837 this->write(to_string(intf.fVariable.fModifiers.fLayout.fSet));
Timothy Liang057c3902018-08-08 10:48:45 -0400838#else
839 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
840#endif
Timothy Lianga06f2152018-05-24 15:33:31 -0400841 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400842 }
843 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500844 if (fProgram.fKind == Program::kFragment_Kind) {
845 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400846#ifdef SK_MOLTENVK
847 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(0)]]");
848#else
849 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
850#endif
Ethan Nicholasf931e402019-07-26 15:40:33 -0400851 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400852 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400853 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400854 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400855 } else if (fProgram.fKind == Program::kVertex_Kind) {
856 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400857 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400858 separator = ", ";
859 } else {
860 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400861 this->write(" ");
862 this->writeName(f.fDeclaration.fName);
863 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400864 Requirements requirements = this->requirements(f.fDeclaration);
865 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400866 this->write("Inputs _in");
867 separator = ", ";
868 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400869 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400870 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400871 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400872 separator = ", ";
873 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400874 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400875 this->write(separator);
876 this->write("Uniforms _uniforms");
877 separator = ", ";
878 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400879 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400880 this->write(separator);
881 this->write("thread Globals* _globals");
882 separator = ", ";
883 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400884 if (requirements & kFragCoord_Requirement) {
885 this->write(separator);
886 this->write("float4 _fragCoord");
887 separator = ", ";
888 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400889 }
890 for (const auto& param : f.fDeclaration.fParameters) {
891 this->write(separator);
892 separator = ", ";
893 this->writeModifiers(param->fModifiers, false);
894 std::vector<int> sizes;
895 const Type* type = &param->fType;
896 while (Type::kArray_Kind == type->kind()) {
897 sizes.push_back(type->columns());
898 type = &type->componentType();
899 }
900 this->writeType(*type);
901 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
902 this->write("*");
903 }
Timothy Liang651286f2018-06-07 09:55:33 -0400904 this->write(" ");
905 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400906 for (int s : sizes) {
907 if (s <= 0) {
908 this->write("[]");
909 } else {
910 this->write("[" + to_string(s) + "]");
911 }
912 }
913 }
914 this->writeLine(") {");
915
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400916 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -0400917
Ethan Nicholascc305772017-10-13 16:17:45 -0400918 if ("main" == f.fDeclaration.fName) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400919 if (fNeedsGlobalStructInit) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500920 this->writeLine(" Globals globalStruct{");
921 const char* separator = "";
Timothy Liang7d637782018-06-05 09:58:07 -0400922 for (const auto& intf: fInterfaceBlockNameMap) {
923 const auto& intfName = intf.second;
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500924 this->write(separator);
925 separator = ", ";
926 this->write("&");
Timothy Liang651286f2018-06-07 09:55:33 -0400927 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400928 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400929 for (const auto& var: fInitNonConstGlobalVars) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500930 this->write(separator);
931 separator = ", ";
Timothy Liangee84fe12018-05-18 14:38:19 -0400932 this->writeVarInitializer(*var->fVar, *var->fValue);
Timothy Liangee84fe12018-05-18 14:38:19 -0400933 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400934 for (const auto& texture: fTextures) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500935 this->write(separator);
936 separator = ", ";
Timothy Liang651286f2018-06-07 09:55:33 -0400937 this->writeName(texture->fName);
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500938 this->write(separator);
Timothy Liang651286f2018-06-07 09:55:33 -0400939 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400940 this->write(SAMPLER_SUFFIX);
Timothy Liangee84fe12018-05-18 14:38:19 -0400941 }
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500942 this->writeLine("};");
943 this->writeLine(" thread Globals* _globals = &globalStruct;");
944 this->writeLine(" (void)_globals;");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400945 }
Timothy Liang7d637782018-06-05 09:58:07 -0400946 this->writeLine(" Outputs _outputStruct;");
947 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400948 }
949 fFunctionHeader = "";
950 OutputStream* oldOut = fOut;
951 StringStream buffer;
952 fOut = &buffer;
953 fIndentation++;
954 this->writeStatements(((Block&) *f.fBody).fStatements);
955 if ("main" == f.fDeclaration.fName) {
956 switch (fProgram.fKind) {
957 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -0400958 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400959 break;
960 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400961 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -0400962 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -0400963 break;
964 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400965 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400966 }
967 }
968 fIndentation--;
969 this->writeLine("}");
970
971 fOut = oldOut;
972 this->write(fFunctionHeader);
973 this->write(buffer.str());
974}
975
976void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
977 bool globalContext) {
978 if (modifiers.fFlags & Modifiers::kOut_Flag) {
979 this->write("thread ");
980 }
981 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400982 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400983 }
984}
985
986void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
987 if ("sk_PerVertex" == intf.fTypeName) {
988 return;
989 }
990 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -0400991 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400992 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -0400993 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -0400994 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -0400995 while (Type::kArray_Kind == structType->kind()) {
996 structType = &structType->componentType();
997 }
Timothy Liangdc89f192018-06-13 09:20:31 -0400998 fIndentation++;
999 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001000 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001001 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001002 }
1003 fIndentation--;
1004 this->write("}");
1005 if (intf.fInstanceName.size()) {
1006 this->write(" ");
1007 this->write(intf.fInstanceName);
1008 for (const auto& size : intf.fSizes) {
1009 this->write("[");
1010 if (size) {
1011 this->writeExpression(*size, kTopLevel_Precedence);
1012 }
1013 this->write("]");
1014 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001015 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1016 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001017 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001018 }
1019 this->writeLine(";");
1020}
1021
Timothy Liangdc89f192018-06-13 09:20:31 -04001022void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1023 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001024#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001025 MemoryLayout memoryLayout(MemoryLayout::k140_Standard);
Timothy Liang609fbe32018-08-10 16:40:49 -04001026#else
1027 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
1028#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001029 int currentOffset = 0;
1030 for (const auto& field: fields) {
1031 int fieldOffset = field.fModifiers.fLayout.fOffset;
1032 const Type* fieldType = field.fType;
1033 if (fieldOffset != -1) {
1034 if (currentOffset > fieldOffset) {
1035 fErrors.error(parentOffset,
1036 "offset of field '" + field.fName + "' must be at least " +
1037 to_string((int) currentOffset));
1038 } else if (currentOffset < fieldOffset) {
1039 this->write("char pad");
1040 this->write(to_string(fPaddingCount++));
1041 this->write("[");
1042 this->write(to_string(fieldOffset - currentOffset));
1043 this->writeLine("];");
1044 currentOffset = fieldOffset;
1045 }
1046 int alignment = memoryLayout.alignment(*fieldType);
1047 if (fieldOffset % alignment) {
1048 fErrors.error(parentOffset,
1049 "offset of field '" + field.fName + "' must be a multiple of " +
1050 to_string((int) alignment));
1051 }
1052 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001053#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001054 if (fieldType->kind() == Type::kVector_Kind &&
1055 fieldType->columns() == 3) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001056 SkASSERT(memoryLayout.size(*fieldType) == 3);
Timothy Liangdc89f192018-06-13 09:20:31 -04001057 // Pack all vec3 types so that their size in bytes will match what was expected in the
1058 // original SkSL code since MSL has vec3 sizes equal to 4 * component type, while SkSL
1059 // has vec3 equal to 3 * component type.
Timothy Liang609fbe32018-08-10 16:40:49 -04001060
1061 // FIXME - Packed vectors can't be accessed by swizzles, but can be indexed into. A
1062 // combination of this being a problem which only occurs when using MoltenVK and the
1063 // fact that we haven't swizzled a vec3 yet means that this problem hasn't been
1064 // addressed.
Timothy Liangdc89f192018-06-13 09:20:31 -04001065 this->write(PACKED_PREFIX);
1066 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001067#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001068 currentOffset += memoryLayout.size(*fieldType);
1069 std::vector<int> sizes;
1070 while (fieldType->kind() == Type::kArray_Kind) {
1071 sizes.push_back(fieldType->columns());
1072 fieldType = &fieldType->componentType();
1073 }
1074 this->writeModifiers(field.fModifiers, false);
1075 this->writeType(*fieldType);
1076 this->write(" ");
1077 this->writeName(field.fName);
1078 for (int s : sizes) {
1079 if (s <= 0) {
1080 this->write("[]");
1081 } else {
1082 this->write("[" + to_string(s) + "]");
1083 }
1084 }
1085 this->writeLine(";");
1086 if (parentIntf) {
1087 fInterfaceBlockMap[&field] = parentIntf;
1088 }
1089 }
1090}
1091
Ethan Nicholascc305772017-10-13 16:17:45 -04001092void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1093 this->writeExpression(value, kTopLevel_Precedence);
1094}
1095
Timothy Liang651286f2018-06-07 09:55:33 -04001096void MetalCodeGenerator::writeName(const String& name) {
1097 if (fReservedWords.find(name) != fReservedWords.end()) {
1098 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1099 }
1100 this->write(name);
1101}
1102
Ethan Nicholascc305772017-10-13 16:17:45 -04001103void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001104 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001105 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001106 for (const auto& stmt : decl.fVars) {
1107 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001108 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001109 continue;
1110 }
1111 if (wroteType) {
1112 this->write(", ");
1113 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001114 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001115 this->writeType(decl.fBaseType);
1116 this->write(" ");
1117 wroteType = true;
1118 }
Timothy Liang651286f2018-06-07 09:55:33 -04001119 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001120 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001121 this->write("[");
1122 if (size) {
1123 this->writeExpression(*size, kTopLevel_Precedence);
1124 }
1125 this->write("]");
1126 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001127 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001128 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001129 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001130 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001131 }
1132 if (wroteType) {
1133 this->write(";");
1134 }
1135}
1136
1137void MetalCodeGenerator::writeStatement(const Statement& s) {
1138 switch (s.fKind) {
1139 case Statement::kBlock_Kind:
1140 this->writeBlock((Block&) s);
1141 break;
1142 case Statement::kExpression_Kind:
1143 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1144 this->write(";");
1145 break;
1146 case Statement::kReturn_Kind:
1147 this->writeReturnStatement((ReturnStatement&) s);
1148 break;
1149 case Statement::kVarDeclarations_Kind:
1150 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1151 break;
1152 case Statement::kIf_Kind:
1153 this->writeIfStatement((IfStatement&) s);
1154 break;
1155 case Statement::kFor_Kind:
1156 this->writeForStatement((ForStatement&) s);
1157 break;
1158 case Statement::kWhile_Kind:
1159 this->writeWhileStatement((WhileStatement&) s);
1160 break;
1161 case Statement::kDo_Kind:
1162 this->writeDoStatement((DoStatement&) s);
1163 break;
1164 case Statement::kSwitch_Kind:
1165 this->writeSwitchStatement((SwitchStatement&) s);
1166 break;
1167 case Statement::kBreak_Kind:
1168 this->write("break;");
1169 break;
1170 case Statement::kContinue_Kind:
1171 this->write("continue;");
1172 break;
1173 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001174 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001175 break;
1176 case Statement::kNop_Kind:
1177 this->write(";");
1178 break;
1179 default:
1180 ABORT("unsupported statement: %s", s.description().c_str());
1181 }
1182}
1183
1184void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1185 for (const auto& s : statements) {
1186 if (!s->isEmpty()) {
1187 this->writeStatement(*s);
1188 this->writeLine();
1189 }
1190 }
1191}
1192
1193void MetalCodeGenerator::writeBlock(const Block& b) {
1194 this->writeLine("{");
1195 fIndentation++;
1196 this->writeStatements(b.fStatements);
1197 fIndentation--;
1198 this->write("}");
1199}
1200
1201void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1202 this->write("if (");
1203 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1204 this->write(") ");
1205 this->writeStatement(*stmt.fIfTrue);
1206 if (stmt.fIfFalse) {
1207 this->write(" else ");
1208 this->writeStatement(*stmt.fIfFalse);
1209 }
1210}
1211
1212void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1213 this->write("for (");
1214 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1215 this->writeStatement(*f.fInitializer);
1216 } else {
1217 this->write("; ");
1218 }
1219 if (f.fTest) {
1220 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1221 }
1222 this->write("; ");
1223 if (f.fNext) {
1224 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1225 }
1226 this->write(") ");
1227 this->writeStatement(*f.fStatement);
1228}
1229
1230void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1231 this->write("while (");
1232 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1233 this->write(") ");
1234 this->writeStatement(*w.fStatement);
1235}
1236
1237void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1238 this->write("do ");
1239 this->writeStatement(*d.fStatement);
1240 this->write(" while (");
1241 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1242 this->write(");");
1243}
1244
1245void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1246 this->write("switch (");
1247 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1248 this->writeLine(") {");
1249 fIndentation++;
1250 for (const auto& c : s.fCases) {
1251 if (c->fValue) {
1252 this->write("case ");
1253 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1254 this->writeLine(":");
1255 } else {
1256 this->writeLine("default:");
1257 }
1258 fIndentation++;
1259 for (const auto& stmt : c->fStatements) {
1260 this->writeStatement(*stmt);
1261 this->writeLine();
1262 }
1263 fIndentation--;
1264 }
1265 fIndentation--;
1266 this->write("}");
1267}
1268
1269void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1270 this->write("return");
1271 if (r.fExpression) {
1272 this->write(" ");
1273 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1274 }
1275 this->write(";");
1276}
1277
1278void MetalCodeGenerator::writeHeader() {
1279 this->write("#include <metal_stdlib>\n");
1280 this->write("#include <simd/simd.h>\n");
1281 this->write("using namespace metal;\n");
1282}
1283
1284void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001285 for (const auto& e : fProgram) {
1286 if (ProgramElement::kVar_Kind == e.fKind) {
1287 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001288 if (!decls.fVars.size()) {
1289 continue;
1290 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001291 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001292 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1293 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001294 if (-1 == fUniformBuffer) {
1295 this->write("struct Uniforms {\n");
1296 fUniformBuffer = first.fModifiers.fLayout.fSet;
1297 if (-1 == fUniformBuffer) {
1298 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1299 }
1300 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1301 if (-1 == fUniformBuffer) {
1302 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1303 "the same 'layout(set=...)'");
1304 }
1305 }
1306 this->write(" ");
1307 this->writeType(first.fType);
1308 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001309 for (const auto& stmt : decls.fVars) {
1310 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001311 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001312 }
1313 this->write(";\n");
1314 }
1315 }
1316 }
1317 if (-1 != fUniformBuffer) {
1318 this->write("};\n");
1319 }
1320}
1321
1322void MetalCodeGenerator::writeInputStruct() {
1323 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001324 for (const auto& e : fProgram) {
1325 if (ProgramElement::kVar_Kind == e.fKind) {
1326 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001327 if (!decls.fVars.size()) {
1328 continue;
1329 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001330 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001331 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1332 -1 == first.fModifiers.fLayout.fBuiltin) {
1333 this->write(" ");
1334 this->writeType(first.fType);
1335 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001336 for (const auto& stmt : decls.fVars) {
1337 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001338 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001339 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001340 if (fProgram.fKind == Program::kVertex_Kind) {
1341 this->write(" [[attribute(" +
1342 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1343 } else if (fProgram.fKind == Program::kFragment_Kind) {
1344 this->write(" [[user(locn" +
1345 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1346 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001347 }
1348 }
1349 this->write(";\n");
1350 }
1351 }
1352 }
1353 this->write("};\n");
1354}
1355
1356void MetalCodeGenerator::writeOutputStruct() {
1357 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001358 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001359 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001360 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001361 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001362 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001363 for (const auto& e : fProgram) {
1364 if (ProgramElement::kVar_Kind == e.fKind) {
1365 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001366 if (!decls.fVars.size()) {
1367 continue;
1368 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001369 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001370 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1371 -1 == first.fModifiers.fLayout.fBuiltin) {
1372 this->write(" ");
1373 this->writeType(first.fType);
1374 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001375 for (const auto& stmt : decls.fVars) {
1376 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001377 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001378 if (fProgram.fKind == Program::kVertex_Kind) {
1379 this->write(" [[user(locn" +
1380 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1381 } else if (fProgram.fKind == Program::kFragment_Kind) {
1382 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001383 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1384 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1385 if (colorIndex) {
1386 this->write(", index(" + to_string(colorIndex) + ")");
1387 }
1388 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001389 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001390 }
1391 this->write(";\n");
1392 }
1393 }
Timothy Liang7d637782018-06-05 09:58:07 -04001394 }
1395 if (fProgram.fKind == Program::kVertex_Kind) {
1396 this->write(" float sk_PointSize;\n");
1397 }
1398 this->write("};\n");
1399}
1400
1401void MetalCodeGenerator::writeInterfaceBlocks() {
1402 bool wroteInterfaceBlock = false;
1403 for (const auto& e : fProgram) {
1404 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1405 this->writeInterfaceBlock((InterfaceBlock&) e);
1406 wroteInterfaceBlock = true;
1407 }
1408 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001409 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001410 this->writeLine("struct sksl_synthetic_uniforms {");
1411 this->writeLine(" float u_skRTHeight;");
1412 this->writeLine("};");
1413 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001414}
1415
Timothy Liangee84fe12018-05-18 14:38:19 -04001416void MetalCodeGenerator::writeGlobalStruct() {
1417 bool wroteStructDecl = false;
Timothy Liang7d637782018-06-05 09:58:07 -04001418 for (const auto& intf : fInterfaceBlockNameMap) {
1419 if (!wroteStructDecl) {
1420 this->write("struct Globals {\n");
1421 wroteStructDecl = true;
1422 }
1423 fNeedsGlobalStructInit = true;
1424 const auto& intfType = intf.first;
1425 const auto& intfName = intf.second;
1426 this->write(" constant ");
1427 this->write(intfType->fTypeName);
1428 this->write("* ");
Timothy Liang651286f2018-06-07 09:55:33 -04001429 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -04001430 this->write(";\n");
1431 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001432 for (const auto& e : fProgram) {
1433 if (ProgramElement::kVar_Kind == e.fKind) {
1434 VarDeclarations& decls = (VarDeclarations&) e;
1435 if (!decls.fVars.size()) {
1436 continue;
1437 }
1438 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001439 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1440 first.fType.kind() == Type::kSampler_Kind) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001441 if (!wroteStructDecl) {
1442 this->write("struct Globals {\n");
1443 wroteStructDecl = true;
1444 }
1445 fNeedsGlobalStructInit = true;
1446 this->write(" ");
1447 this->writeType(first.fType);
1448 this->write(" ");
1449 for (const auto& stmt : decls.fVars) {
1450 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001451 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001452 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1453 fTextures.push_back(var.fVar);
1454 this->write(";\n");
1455 this->write(" sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -04001456 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001457 this->write(SAMPLER_SUFFIX);
1458 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001459 if (var.fValue) {
1460 fInitNonConstGlobalVars.push_back(&var);
1461 }
1462 }
1463 this->write(";\n");
1464 }
1465 }
1466 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001467 if (wroteStructDecl) {
1468 this->write("};\n");
1469 }
1470}
1471
Ethan Nicholascc305772017-10-13 16:17:45 -04001472void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1473 switch (e.fKind) {
1474 case ProgramElement::kExtension_Kind:
1475 break;
1476 case ProgramElement::kVar_Kind: {
1477 VarDeclarations& decl = (VarDeclarations&) e;
1478 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001479 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001480 if (-1 == builtin) {
1481 // normal var
1482 this->writeVarDeclarations(decl, true);
1483 this->writeLine();
1484 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1485 // ignore
1486 }
1487 }
1488 break;
1489 }
1490 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001491 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001492 break;
1493 case ProgramElement::kFunction_Kind:
1494 this->writeFunction((FunctionDefinition&) e);
1495 break;
1496 case ProgramElement::kModifiers_Kind:
1497 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1498 this->writeLine(";");
1499 break;
1500 default:
1501 printf("%s\n", e.description().c_str());
1502 ABORT("unsupported program element");
1503 }
1504}
1505
1506MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression& e) {
1507 switch (e.fKind) {
1508 case Expression::kFunctionCall_Kind: {
1509 const FunctionCall& f = (const FunctionCall&) e;
1510 Requirements result = this->requirements(f.fFunction);
1511 for (const auto& e : f.fArguments) {
1512 result |= this->requirements(*e);
1513 }
1514 return result;
1515 }
1516 case Expression::kConstructor_Kind: {
1517 const Constructor& c = (const Constructor&) e;
1518 Requirements result = kNo_Requirements;
1519 for (const auto& e : c.fArguments) {
1520 result |= this->requirements(*e);
1521 }
1522 return result;
1523 }
Timothy Liang7d637782018-06-05 09:58:07 -04001524 case Expression::kFieldAccess_Kind: {
1525 const FieldAccess& f = (const FieldAccess&) e;
1526 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1527 return kGlobals_Requirement;
1528 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001529 return this->requirements(*((const FieldAccess&) e).fBase);
Timothy Liang7d637782018-06-05 09:58:07 -04001530 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001531 case Expression::kSwizzle_Kind:
1532 return this->requirements(*((const Swizzle&) e).fBase);
1533 case Expression::kBinary_Kind: {
1534 const BinaryExpression& b = (const BinaryExpression&) e;
1535 return this->requirements(*b.fLeft) | this->requirements(*b.fRight);
1536 }
1537 case Expression::kIndex_Kind: {
1538 const IndexExpression& idx = (const IndexExpression&) e;
1539 return this->requirements(*idx.fBase) | this->requirements(*idx.fIndex);
1540 }
1541 case Expression::kPrefix_Kind:
1542 return this->requirements(*((const PrefixExpression&) e).fOperand);
1543 case Expression::kPostfix_Kind:
1544 return this->requirements(*((const PostfixExpression&) e).fOperand);
1545 case Expression::kTernary_Kind: {
1546 const TernaryExpression& t = (const TernaryExpression&) e;
1547 return this->requirements(*t.fTest) | this->requirements(*t.fIfTrue) |
1548 this->requirements(*t.fIfFalse);
1549 }
1550 case Expression::kVariableReference_Kind: {
1551 const VariableReference& v = (const VariableReference&) e;
1552 Requirements result = kNo_Requirements;
1553 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001554 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001555 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1556 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1557 result = kInputs_Requirement;
1558 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1559 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001560 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1561 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001562 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001563 } else {
1564 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001565 }
1566 }
1567 return result;
1568 }
1569 default:
1570 return kNo_Requirements;
1571 }
1572}
1573
1574MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement& s) {
1575 switch (s.fKind) {
1576 case Statement::kBlock_Kind: {
1577 Requirements result = kNo_Requirements;
1578 for (const auto& child : ((const Block&) s).fStatements) {
1579 result |= this->requirements(*child);
1580 }
1581 return result;
1582 }
Timothy Liang7d637782018-06-05 09:58:07 -04001583 case Statement::kVarDeclaration_Kind: {
1584 Requirements result = kNo_Requirements;
1585 const VarDeclaration& var = (const VarDeclaration&) s;
1586 if (var.fValue) {
1587 result = this->requirements(*var.fValue);
1588 }
1589 return result;
1590 }
1591 case Statement::kVarDeclarations_Kind: {
1592 Requirements result = kNo_Requirements;
1593 const VarDeclarations& decls = *((const VarDeclarationsStatement&) s).fDeclaration;
1594 for (const auto& stmt : decls.fVars) {
1595 result |= this->requirements(*stmt);
1596 }
1597 return result;
1598 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001599 case Statement::kExpression_Kind:
1600 return this->requirements(*((const ExpressionStatement&) s).fExpression);
1601 case Statement::kReturn_Kind: {
1602 const ReturnStatement& r = (const ReturnStatement&) s;
1603 if (r.fExpression) {
1604 return this->requirements(*r.fExpression);
1605 }
1606 return kNo_Requirements;
1607 }
1608 case Statement::kIf_Kind: {
1609 const IfStatement& i = (const IfStatement&) s;
1610 return this->requirements(*i.fTest) |
1611 this->requirements(*i.fIfTrue) |
Ethan Nicholasf931e402019-07-26 15:40:33 -04001612 (i.fIfFalse ? this->requirements(*i.fIfFalse) : 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001613 }
1614 case Statement::kFor_Kind: {
1615 const ForStatement& f = (const ForStatement&) s;
1616 return this->requirements(*f.fInitializer) |
1617 this->requirements(*f.fTest) |
1618 this->requirements(*f.fNext) |
1619 this->requirements(*f.fStatement);
1620 }
1621 case Statement::kWhile_Kind: {
1622 const WhileStatement& w = (const WhileStatement&) s;
1623 return this->requirements(*w.fTest) |
1624 this->requirements(*w.fStatement);
1625 }
1626 case Statement::kDo_Kind: {
1627 const DoStatement& d = (const DoStatement&) s;
1628 return this->requirements(*d.fTest) |
1629 this->requirements(*d.fStatement);
1630 }
1631 case Statement::kSwitch_Kind: {
1632 const SwitchStatement& sw = (const SwitchStatement&) s;
1633 Requirements result = this->requirements(*sw.fValue);
1634 for (const auto& c : sw.fCases) {
1635 for (const auto& st : c->fStatements) {
1636 result |= this->requirements(*st);
1637 }
1638 }
1639 return result;
1640 }
1641 default:
1642 return kNo_Requirements;
1643 }
1644}
1645
1646MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1647 if (f.fBuiltin) {
1648 return kNo_Requirements;
1649 }
1650 auto found = fRequirements.find(&f);
1651 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001652 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001653 for (const auto& e : fProgram) {
1654 if (ProgramElement::kFunction_Kind == e.fKind) {
1655 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001656 if (&def.fDeclaration == &f) {
1657 Requirements reqs = this->requirements(*def.fBody);
1658 fRequirements[&f] = reqs;
1659 return reqs;
1660 }
1661 }
1662 }
1663 }
1664 return found->second;
1665}
1666
Timothy Liangb8eeb802018-07-23 16:46:16 -04001667bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001668 OutputStream* rawOut = fOut;
1669 fOut = &fHeader;
Timothy Liangb8eeb802018-07-23 16:46:16 -04001670#ifdef SK_MOLTENVK
1671 fOut->write((const char*) &MVKMagicNum, sizeof(MVKMagicNum));
1672#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001673 fProgramKind = fProgram.fKind;
1674 this->writeHeader();
1675 this->writeUniformStruct();
1676 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001677 this->writeOutputStruct();
1678 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001679 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001680 StringStream body;
1681 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001682 for (const auto& e : fProgram) {
1683 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001684 }
1685 fOut = rawOut;
1686
1687 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001688 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001689 write_stringstream(body, *rawOut);
Timothy Liangb8eeb802018-07-23 16:46:16 -04001690#ifdef SK_MOLTENVK
1691 this->write("\0");
1692#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001693 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001694}
1695
1696}