blob: 2b222d8ba1346bfde8b619dff3cbd893f7332a57 [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
18namespace SkSL {
19
Timothy Liangee84fe12018-05-18 14:38:19 -040020void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040021#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
22#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040023 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040024 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050025 fIntrinsicMap[String("equal")] = METAL(Equal);
26 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040027 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
28 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
29 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
30 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040031}
32
Ethan Nicholascc305772017-10-13 16:17:45 -040033void MetalCodeGenerator::write(const char* s) {
34 if (!s[0]) {
35 return;
36 }
37 if (fAtLineStart) {
38 for (int i = 0; i < fIndentation; i++) {
39 fOut->writeText(" ");
40 }
41 }
42 fOut->writeText(s);
43 fAtLineStart = false;
44}
45
46void MetalCodeGenerator::writeLine(const char* s) {
47 this->write(s);
48 fOut->writeText(fLineEnding);
49 fAtLineStart = true;
50}
51
52void MetalCodeGenerator::write(const String& s) {
53 this->write(s.c_str());
54}
55
56void MetalCodeGenerator::writeLine(const String& s) {
57 this->writeLine(s.c_str());
58}
59
60void MetalCodeGenerator::writeLine() {
61 this->writeLine("");
62}
63
64void MetalCodeGenerator::writeExtension(const Extension& ext) {
65 this->writeLine("#extension " + ext.fName + " : enable");
66}
67
Ethan Nicholas45fa8102020-01-13 10:58:49 -050068String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholascc305772017-10-13 16:17:45 -040069 switch (type.kind()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040070 case Type::kVector_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050071 return this->typeName(type.componentType()) + to_string(type.columns());
Timothy Liang43d225f2018-07-19 15:27:13 -040072 case Type::kMatrix_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050073 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
74 to_string(type.rows());
Timothy Liangee84fe12018-05-18 14:38:19 -040075 case Type::kSampler_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050076 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040077 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040078 if (type == *fContext.fHalf_Type) {
79 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050080 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040081 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050082 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040083 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040085 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050086 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040087 }
Ethan Nicholascc305772017-10-13 16:17:45 -040088 }
89}
90
Ethan Nicholas45fa8102020-01-13 10:58:49 -050091void MetalCodeGenerator::writeType(const Type& type) {
92 if (type.kind() == Type::kStruct_Kind) {
93 for (const Type* search : fWrittenStructs) {
94 if (*search == type) {
95 // already written
96 this->write(type.name());
97 return;
98 }
99 }
100 fWrittenStructs.push_back(&type);
101 this->writeLine("struct " + type.name() + " {");
102 fIndentation++;
103 this->writeFields(type.fields(), type.fOffset);
104 fIndentation--;
105 this->write("}");
106 } else {
107 this->write(this->typeName(type));
108 }
109}
110
Ethan Nicholascc305772017-10-13 16:17:45 -0400111void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
112 switch (expr.fKind) {
113 case Expression::kBinary_Kind:
114 this->writeBinaryExpression((BinaryExpression&) expr, parentPrecedence);
115 break;
116 case Expression::kBoolLiteral_Kind:
117 this->writeBoolLiteral((BoolLiteral&) expr);
118 break;
119 case Expression::kConstructor_Kind:
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500120 this->writeConstructor((Constructor&) expr, parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400121 break;
122 case Expression::kIntLiteral_Kind:
123 this->writeIntLiteral((IntLiteral&) expr);
124 break;
125 case Expression::kFieldAccess_Kind:
126 this->writeFieldAccess(((FieldAccess&) expr));
127 break;
128 case Expression::kFloatLiteral_Kind:
129 this->writeFloatLiteral(((FloatLiteral&) expr));
130 break;
131 case Expression::kFunctionCall_Kind:
132 this->writeFunctionCall((FunctionCall&) expr);
133 break;
134 case Expression::kPrefix_Kind:
135 this->writePrefixExpression((PrefixExpression&) expr, parentPrecedence);
136 break;
137 case Expression::kPostfix_Kind:
138 this->writePostfixExpression((PostfixExpression&) expr, parentPrecedence);
139 break;
140 case Expression::kSetting_Kind:
141 this->writeSetting((Setting&) expr);
142 break;
143 case Expression::kSwizzle_Kind:
144 this->writeSwizzle((Swizzle&) expr);
145 break;
146 case Expression::kVariableReference_Kind:
147 this->writeVariableReference((VariableReference&) expr);
148 break;
149 case Expression::kTernary_Kind:
150 this->writeTernaryExpression((TernaryExpression&) expr, parentPrecedence);
151 break;
152 case Expression::kIndex_Kind:
153 this->writeIndexExpression((IndexExpression&) expr);
154 break;
155 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500156#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400157 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500158#endif
159 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 }
161}
162
Timothy Liang6403b0e2018-05-17 10:40:04 -0400163void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400164 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400165 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400166 Intrinsic intrinsic = i->second;
167 int32_t intrinsicId = intrinsic.second;
168 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400169 case kSpecial_IntrinsicKind:
170 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400171 break;
172 case kMetal_IntrinsicKind:
173 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
174 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500175 case kEqual_MetalIntrinsic:
176 this->write(" == ");
177 break;
178 case kNotEqual_MetalIntrinsic:
179 this->write(" != ");
180 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400181 case kLessThan_MetalIntrinsic:
182 this->write(" < ");
183 break;
184 case kLessThanEqual_MetalIntrinsic:
185 this->write(" <= ");
186 break;
187 case kGreaterThan_MetalIntrinsic:
188 this->write(" > ");
189 break;
190 case kGreaterThanEqual_MetalIntrinsic:
191 this->write(" >= ");
192 break;
193 default:
194 ABORT("unsupported metal intrinsic kind");
195 }
196 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
197 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400198 default:
199 ABORT("unsupported intrinsic kind");
200 }
201}
202
Ethan Nicholascc305772017-10-13 16:17:45 -0400203void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400204 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
205 if (entry != fIntrinsicMap.end()) {
206 this->writeIntrinsicCall(c);
207 return;
208 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400209 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
210 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400211 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
212 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500213 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
214 SkASSERT(c.fArguments.size() == 1);
215 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400216 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
217 this->write("dfdx");
218 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700219 // Flipping Y also negates the Y derivatives.
220 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400221 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400222 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400223 }
224 this->write("(");
225 const char* separator = "";
226 if (this->requirements(c.fFunction) & kInputs_Requirement) {
227 this->write("_in");
228 separator = ", ";
229 }
230 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
231 this->write(separator);
232 this->write("_out");
233 separator = ", ";
234 }
235 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
236 this->write(separator);
237 this->write("_uniforms");
238 separator = ", ";
239 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400240 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
241 this->write(separator);
242 this->write("_globals");
243 separator = ", ";
244 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400245 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
246 this->write(separator);
247 this->write("_fragCoord");
248 separator = ", ";
249 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400250 for (size_t i = 0; i < c.fArguments.size(); ++i) {
251 const Expression& arg = *c.fArguments[i];
252 this->write(separator);
253 separator = ", ";
254 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
255 this->write("&");
256 }
257 this->writeExpression(arg, kSequence_Precedence);
258 }
259 this->write(")");
260}
261
Chris Daltondba7aab2018-11-15 10:57:49 -0500262void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500263 String typeName = mat.fType.name();
264 String name = typeName + "_inverse";
265 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500266 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
267 fWrittenIntrinsics.insert(name);
268 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500269 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500270 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
271 "}"
272 ).c_str());
273 }
274 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500275 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
276 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
277 fWrittenIntrinsics.insert(name);
278 fExtraFunctions.writeText((
279 typeName + " " + name + "(" + typeName + " m) {"
280 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
281 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
282 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
283 " float b01 = a22 * a11 - a12 * a21;"
284 " float b11 = -a22 * a10 + a12 * a20;"
285 " float b21 = a21 * a10 - a11 * a20;"
286 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
287 " return " + typeName +
288 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
289 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
290 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
291 " (1/det);"
292 "}"
293 ).c_str());
294 }
295 }
296 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
297 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
298 fWrittenIntrinsics.insert(name);
299 fExtraFunctions.writeText((
300 typeName + " " + name + "(" + typeName + " m) {"
301 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
302 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
303 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
304 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
305 " float b00 = a00 * a11 - a01 * a10;"
306 " float b01 = a00 * a12 - a02 * a10;"
307 " float b02 = a00 * a13 - a03 * a10;"
308 " float b03 = a01 * a12 - a02 * a11;"
309 " float b04 = a01 * a13 - a03 * a11;"
310 " float b05 = a02 * a13 - a03 * a12;"
311 " float b06 = a20 * a31 - a21 * a30;"
312 " float b07 = a20 * a32 - a22 * a30;"
313 " float b08 = a20 * a33 - a23 * a30;"
314 " float b09 = a21 * a32 - a22 * a31;"
315 " float b10 = a21 * a33 - a23 * a31;"
316 " float b11 = a22 * a33 - a23 * a32;"
317 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
318 " b04 * b07 + b05 * b06;"
319 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
320 " a02 * b10 - a01 * b11 - a03 * b09,"
321 " a31 * b05 - a32 * b04 + a33 * b03,"
322 " a22 * b04 - a21 * b05 - a23 * b03,"
323 " a12 * b08 - a10 * b11 - a13 * b07,"
324 " a00 * b11 - a02 * b08 + a03 * b07,"
325 " a32 * b02 - a30 * b05 - a33 * b01,"
326 " a20 * b05 - a22 * b02 + a23 * b01,"
327 " a10 * b10 - a11 * b08 + a13 * b06,"
328 " a01 * b08 - a00 * b10 - a03 * b06,"
329 " a30 * b04 - a31 * b02 + a33 * b00,"
330 " a21 * b02 - a20 * b04 - a23 * b00,"
331 " a11 * b07 - a10 * b09 - a12 * b06,"
332 " a00 * b09 - a01 * b07 + a02 * b06,"
333 " a31 * b01 - a30 * b03 - a32 * b00,"
334 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
335 "}"
336 ).c_str());
337 }
338 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500339 this->write(name);
340}
341
Timothy Liang6403b0e2018-05-17 10:40:04 -0400342void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
343 switch (kind) {
344 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400345 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400346 this->write(".sample(");
347 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
348 this->write(SAMPLER_SUFFIX);
349 this->write(", ");
Timothy Liangee84fe12018-05-18 14:38:19 -0400350 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500351 // have to store the vector in a temp variable to avoid double evaluating it
352 String tmpVar = "tmpCoord" + to_string(fVarCount++);
353 this->fFunctionHeader += " " + this->typeName(c.fArguments[1]->fType) + " " +
354 tmpVar + ";\n";
355 this->write("(" + tmpVar + " = ");
356 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
357 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400358 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400359 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500360 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400361 this->write(")");
362 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400363 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500364 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400365 // 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 -0500366 String tmpX = "tmpX" + to_string(fVarCount++);
367 String tmpY = "tmpY" + to_string(fVarCount++);
368 this->fFunctionHeader += " " + this->typeName(c.fArguments[0]->fType) + " " + tmpX +
369 ", " + tmpY + ";\n";
370 this->write("(" + tmpX + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400371 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500372 this->write(", " + tmpY + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400373 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500374 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400375 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500376 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400377 default:
378 ABORT("unsupported special intrinsic kind");
379 }
380}
381
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500382// If it hasn't already been written, writes a constructor for 'matrix' which takes a single value
383// of type 'arg'.
384String MetalCodeGenerator::getMatrixConstructHelper(const Type& matrix, const Type& arg) {
385 String key = matrix.name() + arg.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500386 auto found = fHelpers.find(key);
387 if (found != fHelpers.end()) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500388 return found->second;
Ethan Nicholascc305772017-10-13 16:17:45 -0400389 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500390 String name;
391 int columns = matrix.columns();
392 int rows = matrix.rows();
393 if (arg.isNumber()) {
394 // creating a matrix from a single scalar value
395 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float";
396 fExtraFunctions.printf("float%dx%d %s(float x) {\n",
397 columns, rows, name.c_str());
398 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
399 for (int i = 0; i < columns; ++i) {
400 if (i > 0) {
401 fExtraFunctions.writeText(", ");
402 }
403 fExtraFunctions.printf("float%d(", rows);
404 for (int j = 0; j < rows; ++j) {
405 if (j > 0) {
406 fExtraFunctions.writeText(", ");
407 }
408 if (i == j) {
409 fExtraFunctions.writeText("x");
410 } else {
411 fExtraFunctions.writeText("0");
412 }
413 }
414 fExtraFunctions.writeText(")");
415 }
416 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500417 } else if (arg.kind() == Type::kMatrix_Kind) {
418 // creating a matrix from another matrix
419 int argColumns = arg.columns();
420 int argRows = arg.rows();
421 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float" +
422 to_string(argColumns) + "x" + to_string(argRows);
423 fExtraFunctions.printf("float%dx%d %s(float%dx%d m) {\n",
424 columns, rows, name.c_str(), argColumns, argRows);
425 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
426 for (int i = 0; i < columns; ++i) {
427 if (i > 0) {
428 fExtraFunctions.writeText(", ");
429 }
430 fExtraFunctions.printf("float%d(", rows);
431 for (int j = 0; j < rows; ++j) {
432 if (j > 0) {
433 fExtraFunctions.writeText(", ");
434 }
435 if (i < argColumns && j < argRows) {
436 fExtraFunctions.printf("m[%d][%d]", i, j);
437 } else {
438 fExtraFunctions.writeText("0");
439 }
440 }
441 fExtraFunctions.writeText(")");
442 }
443 fExtraFunctions.writeText(");\n}\n");
444 } else if (matrix.rows() == 2 && matrix.columns() == 2 && arg == *fContext.fFloat4_Type) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500445 // float2x2(float4) doesn't work, need to split it into float2x2(float2, float2)
446 name = "float2x2_from_float4";
447 fExtraFunctions.printf(
448 "float2x2 %s(float4 v) {\n"
449 " return float2x2(float2(v[0], v[1]), float2(v[2], v[3]));\n"
450 "}\n",
451 name.c_str()
452 );
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500453 } else {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500454 SkASSERT(false);
455 name = "<error>";
456 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500457 fHelpers[key] = name;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500458 return name;
459}
460
461bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
462 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
463 return false;
464 }
465 if (t1.columns() > 1) {
466 return this->canCoerce(t1.componentType(), t2.componentType());
467 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500468 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500469}
470
471void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
472 if (c.fArguments.size() == 1 && this->canCoerce(c.fType, c.fArguments[0]->fType)) {
473 this->writeExpression(*c.fArguments[0], parentPrecedence);
474 return;
475 }
476 if (c.fType.kind() == Type::kMatrix_Kind && c.fArguments.size() == 1) {
477 const Expression& arg = *c.fArguments[0];
478 String name = this->getMatrixConstructHelper(c.fType, arg.fType);
479 this->write(name);
480 this->write("(");
481 this->writeExpression(arg, kSequence_Precedence);
482 this->write(")");
483 } else {
484 this->writeType(c.fType);
485 this->write("(");
486 const char* separator = "";
487 int scalarCount = 0;
488 for (const auto& arg : c.fArguments) {
489 this->write(separator);
490 separator = ", ";
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500491 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() != c.fType.rows()) {
492 // merge scalars and smaller vectors together
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500493 if (!scalarCount) {
494 this->writeType(c.fType.componentType());
495 this->write(to_string(c.fType.rows()));
496 this->write("(");
497 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500498 scalarCount += arg->fType.columns();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500499 }
500 this->writeExpression(*arg, kSequence_Precedence);
501 if (scalarCount && scalarCount == c.fType.rows()) {
502 this->write(")");
503 scalarCount = 0;
504 }
505 }
506 this->write(")");
507 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400508}
509
510void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400511 if (fRTHeightName.length()) {
512 this->write("float4(_fragCoord.x, ");
513 this->write(fRTHeightName.c_str());
514 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500515 } else {
516 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
517 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400518}
519
520void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
521 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
522 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400523 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400524 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400525 case SK_FRAGCOORD_BUILTIN:
526 this->writeFragCoord();
527 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400528 case SK_VERTEXID_BUILTIN:
529 this->write("sk_VertexID");
530 break;
531 case SK_INSTANCEID_BUILTIN:
532 this->write("sk_InstanceID");
533 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400534 case SK_CLOCKWISE_BUILTIN:
535 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400536 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400537 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
538 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400539 default:
540 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
541 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
542 this->write("_in.");
543 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400544 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400545 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
546 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400547 this->write("_uniforms.");
548 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400549 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400550 }
551 }
Timothy Liang651286f2018-06-07 09:55:33 -0400552 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400553 }
554}
555
556void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
557 this->writeExpression(*expr.fBase, kPostfix_Precedence);
558 this->write("[");
559 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
560 this->write("]");
561}
562
563void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400564 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400565 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
566 this->writeExpression(*f.fBase, kPostfix_Precedence);
567 this->write(".");
568 }
Timothy Liang7d637782018-06-05 09:58:07 -0400569 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400570 case SK_CLIPDISTANCE_BUILTIN:
571 this->write("gl_ClipDistance");
572 break;
573 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400574 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400575 break;
576 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400577 if (field->fName == "sk_PointSize") {
578 this->write("_out->sk_PointSize");
579 } else {
580 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
581 this->write("_globals->");
582 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
583 this->write("->");
584 }
Timothy Liang651286f2018-06-07 09:55:33 -0400585 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400586 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400587 }
588}
589
590void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500591 int last = swizzle.fComponents.back();
592 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
593 this->writeType(swizzle.fType);
594 this->write("(");
595 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400596 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
597 this->write(".");
598 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500599 if (c >= 0) {
600 this->write(&("x\0y\0z\0w\0"[c * 2]));
601 }
602 }
603 if (last == SKSL_SWIZZLE_0) {
604 this->write(", 0)");
605 }
606 else if (last == SKSL_SWIZZLE_1) {
607 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400608 }
609}
610
611MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
612 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400613 case Token::Kind::TK_STAR: // fall through
614 case Token::Kind::TK_SLASH: // fall through
615 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
616 case Token::Kind::TK_PLUS: // fall through
617 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
618 case Token::Kind::TK_SHL: // fall through
619 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
620 case Token::Kind::TK_LT: // fall through
621 case Token::Kind::TK_GT: // fall through
622 case Token::Kind::TK_LTEQ: // fall through
623 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
624 case Token::Kind::TK_EQEQ: // fall through
625 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
626 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
627 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
628 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
629 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
630 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
631 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
632 case Token::Kind::TK_EQ: // fall through
633 case Token::Kind::TK_PLUSEQ: // fall through
634 case Token::Kind::TK_MINUSEQ: // fall through
635 case Token::Kind::TK_STAREQ: // fall through
636 case Token::Kind::TK_SLASHEQ: // fall through
637 case Token::Kind::TK_PERCENTEQ: // fall through
638 case Token::Kind::TK_SHLEQ: // fall through
639 case Token::Kind::TK_SHREQ: // fall through
640 case Token::Kind::TK_LOGICALANDEQ: // fall through
641 case Token::Kind::TK_LOGICALXOREQ: // fall through
642 case Token::Kind::TK_LOGICALOREQ: // fall through
643 case Token::Kind::TK_BITWISEANDEQ: // fall through
644 case Token::Kind::TK_BITWISEXOREQ: // fall through
645 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
646 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400647 default: ABORT("unsupported binary operator");
648 }
649}
650
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500651void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
652 const Type& result) {
653 String key = "TimesEqual" + left.name() + right.name();
654 if (fHelpers.find(key) == fHelpers.end()) {
655 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
656 " left = left * right;\n"
657 " return left;\n"
658 "}", result.name().c_str(), left.name().c_str(),
659 right.name().c_str());
660 }
661}
662
Ethan Nicholascc305772017-10-13 16:17:45 -0400663void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
664 Precedence parentPrecedence) {
665 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500666 bool needParens = precedence >= parentPrecedence;
667 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400668 case Token::Kind::TK_EQEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500669 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
670 this->write("all");
671 needParens = true;
672 }
673 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400674 case Token::Kind::TK_NEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500675 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400676 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500677 needParens = true;
678 }
679 break;
680 default:
681 break;
682 }
683 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400684 this->write("(");
685 }
686 if (Compiler::IsAssignment(b.fOperator) &&
687 Expression::kVariableReference_Kind == b.fLeft->fKind &&
688 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
689 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
690 // writing to an out parameter. Since we have to turn those into pointers, we have to
691 // dereference it here.
692 this->write("*");
693 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400694 if (b.fOperator == Token::Kind::TK_STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500695 b.fRight->fType.kind() == Type::kMatrix_Kind) {
696 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
697 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400698 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400699 if (b.fOperator != Token::Kind::TK_EQ && Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholascc305772017-10-13 16:17:45 -0400700 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
701 // This doesn't compile in Metal:
702 // float4 x = float4(1);
703 // x.xy *= float2x2(...);
704 // with the error message "non-const reference cannot bind to vector element",
705 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
706 // as long as the LHS has no side effects, and hope for the best otherwise.
707 this->write(" = ");
708 this->writeExpression(*b.fLeft, kAssignment_Precedence);
709 this->write(" ");
710 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400711 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400712 this->write(op.substr(0, op.size() - 1).c_str());
713 this->write(" ");
714 } else {
715 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
716 }
717 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500718 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400719 this->write(")");
720 }
721}
722
723void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
724 Precedence parentPrecedence) {
725 if (kTernary_Precedence >= parentPrecedence) {
726 this->write("(");
727 }
728 this->writeExpression(*t.fTest, kTernary_Precedence);
729 this->write(" ? ");
730 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
731 this->write(" : ");
732 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
733 if (kTernary_Precedence >= parentPrecedence) {
734 this->write(")");
735 }
736}
737
738void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
739 Precedence parentPrecedence) {
740 if (kPrefix_Precedence >= parentPrecedence) {
741 this->write("(");
742 }
743 this->write(Compiler::OperatorName(p.fOperator));
744 this->writeExpression(*p.fOperand, kPrefix_Precedence);
745 if (kPrefix_Precedence >= parentPrecedence) {
746 this->write(")");
747 }
748}
749
750void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
751 Precedence parentPrecedence) {
752 if (kPostfix_Precedence >= parentPrecedence) {
753 this->write("(");
754 }
755 this->writeExpression(*p.fOperand, kPostfix_Precedence);
756 this->write(Compiler::OperatorName(p.fOperator));
757 if (kPostfix_Precedence >= parentPrecedence) {
758 this->write(")");
759 }
760}
761
762void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
763 this->write(b.fValue ? "true" : "false");
764}
765
766void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
767 if (i.fType == *fContext.fUInt_Type) {
768 this->write(to_string(i.fValue & 0xffffffff) + "u");
769 } else {
770 this->write(to_string((int32_t) i.fValue));
771 }
772}
773
774void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
775 this->write(to_string(f.fValue));
776}
777
778void MetalCodeGenerator::writeSetting(const Setting& s) {
779 ABORT("internal error; setting was not folded to a constant during compilation\n");
780}
781
782void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400783 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400784 const char* separator = "";
785 if ("main" == f.fDeclaration.fName) {
786 switch (fProgram.fKind) {
787 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400788 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400789 break;
790 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400791 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400792 break;
793 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400794 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400795 }
796 this->write("(Inputs _in [[stage_in]]");
797 if (-1 != fUniformBuffer) {
798 this->write(", constant Uniforms& _uniforms [[buffer(" +
799 to_string(fUniformBuffer) + ")]]");
800 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400801 for (const auto& e : fProgram) {
802 if (ProgramElement::kVar_Kind == e.fKind) {
803 VarDeclarations& decls = (VarDeclarations&) e;
804 if (!decls.fVars.size()) {
805 continue;
806 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400807 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400808 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400809 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
Timothy Liang7d637782018-06-05 09:58:07 -0400810 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400811 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400812 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400813 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
814 this->write(")]]");
815 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400816 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400817 this->write(SAMPLER_SUFFIX);
818 this->write("[[sampler(");
819 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400820 this->write(")]]");
821 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400822 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400823 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
824 InterfaceBlock& intf = (InterfaceBlock&) e;
825 if ("sk_PerVertex" == intf.fTypeName) {
826 continue;
827 }
828 this->write(", constant ");
829 this->writeType(intf.fVariable.fType);
830 this->write("& " );
831 this->write(fInterfaceBlockNameMap[&intf]);
832 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400833 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400834 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400835 }
836 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500837 if (fProgram.fKind == Program::kFragment_Kind) {
838 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400839 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400840 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400841 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400842 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400843 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400844 } else if (fProgram.fKind == Program::kVertex_Kind) {
845 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400846 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400847 separator = ", ";
848 } else {
849 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400850 this->write(" ");
851 this->writeName(f.fDeclaration.fName);
852 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400853 Requirements requirements = this->requirements(f.fDeclaration);
854 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400855 this->write("Inputs _in");
856 separator = ", ";
857 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400858 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400859 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400860 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400861 separator = ", ";
862 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400863 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400864 this->write(separator);
865 this->write("Uniforms _uniforms");
866 separator = ", ";
867 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400868 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400869 this->write(separator);
870 this->write("thread Globals* _globals");
871 separator = ", ";
872 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400873 if (requirements & kFragCoord_Requirement) {
874 this->write(separator);
875 this->write("float4 _fragCoord");
876 separator = ", ";
877 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400878 }
879 for (const auto& param : f.fDeclaration.fParameters) {
880 this->write(separator);
881 separator = ", ";
882 this->writeModifiers(param->fModifiers, false);
883 std::vector<int> sizes;
884 const Type* type = &param->fType;
885 while (Type::kArray_Kind == type->kind()) {
886 sizes.push_back(type->columns());
887 type = &type->componentType();
888 }
889 this->writeType(*type);
890 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
891 this->write("*");
892 }
Timothy Liang651286f2018-06-07 09:55:33 -0400893 this->write(" ");
894 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400895 for (int s : sizes) {
896 if (s <= 0) {
897 this->write("[]");
898 } else {
899 this->write("[" + to_string(s) + "]");
900 }
901 }
902 }
903 this->writeLine(") {");
904
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400905 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -0400906
Ethan Nicholascc305772017-10-13 16:17:45 -0400907 if ("main" == f.fDeclaration.fName) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400908 if (fNeedsGlobalStructInit) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500909 this->writeLine(" Globals globalStruct{");
910 const char* separator = "";
Timothy Liang7d637782018-06-05 09:58:07 -0400911 for (const auto& intf: fInterfaceBlockNameMap) {
912 const auto& intfName = intf.second;
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500913 this->write(separator);
914 separator = ", ";
915 this->write("&");
Timothy Liang651286f2018-06-07 09:55:33 -0400916 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400917 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400918 for (const auto& var: fInitNonConstGlobalVars) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500919 this->write(separator);
920 separator = ", ";
Timothy Liangee84fe12018-05-18 14:38:19 -0400921 this->writeVarInitializer(*var->fVar, *var->fValue);
Timothy Liangee84fe12018-05-18 14:38:19 -0400922 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400923 for (const auto& texture: fTextures) {
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500924 this->write(separator);
925 separator = ", ";
Timothy Liang651286f2018-06-07 09:55:33 -0400926 this->writeName(texture->fName);
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500927 this->write(separator);
Timothy Liang651286f2018-06-07 09:55:33 -0400928 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400929 this->write(SAMPLER_SUFFIX);
Timothy Liangee84fe12018-05-18 14:38:19 -0400930 }
Ethan Nicholasb47eb182019-12-20 10:49:41 -0500931 this->writeLine("};");
932 this->writeLine(" thread Globals* _globals = &globalStruct;");
933 this->writeLine(" (void)_globals;");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400934 }
Timothy Liang7d637782018-06-05 09:58:07 -0400935 this->writeLine(" Outputs _outputStruct;");
936 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400937 }
938 fFunctionHeader = "";
939 OutputStream* oldOut = fOut;
940 StringStream buffer;
941 fOut = &buffer;
942 fIndentation++;
943 this->writeStatements(((Block&) *f.fBody).fStatements);
944 if ("main" == f.fDeclaration.fName) {
945 switch (fProgram.fKind) {
946 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -0400947 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400948 break;
949 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400950 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -0400951 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -0400952 break;
953 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400954 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400955 }
956 }
957 fIndentation--;
958 this->writeLine("}");
959
960 fOut = oldOut;
961 this->write(fFunctionHeader);
962 this->write(buffer.str());
963}
964
965void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
966 bool globalContext) {
967 if (modifiers.fFlags & Modifiers::kOut_Flag) {
968 this->write("thread ");
969 }
970 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400971 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400972 }
973}
974
975void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
976 if ("sk_PerVertex" == intf.fTypeName) {
977 return;
978 }
979 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -0400980 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400981 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -0400982 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -0400983 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -0400984 while (Type::kArray_Kind == structType->kind()) {
985 structType = &structType->componentType();
986 }
Timothy Liangdc89f192018-06-13 09:20:31 -0400987 fIndentation++;
988 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -0500989 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -0400990 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400991 }
992 fIndentation--;
993 this->write("}");
994 if (intf.fInstanceName.size()) {
995 this->write(" ");
996 this->write(intf.fInstanceName);
997 for (const auto& size : intf.fSizes) {
998 this->write("[");
999 if (size) {
1000 this->writeExpression(*size, kTopLevel_Precedence);
1001 }
1002 this->write("]");
1003 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001004 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1005 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001006 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001007 }
1008 this->writeLine(";");
1009}
1010
Timothy Liangdc89f192018-06-13 09:20:31 -04001011void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1012 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001013 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001014 int currentOffset = 0;
1015 for (const auto& field: fields) {
1016 int fieldOffset = field.fModifiers.fLayout.fOffset;
1017 const Type* fieldType = field.fType;
1018 if (fieldOffset != -1) {
1019 if (currentOffset > fieldOffset) {
1020 fErrors.error(parentOffset,
1021 "offset of field '" + field.fName + "' must be at least " +
1022 to_string((int) currentOffset));
1023 } else if (currentOffset < fieldOffset) {
1024 this->write("char pad");
1025 this->write(to_string(fPaddingCount++));
1026 this->write("[");
1027 this->write(to_string(fieldOffset - currentOffset));
1028 this->writeLine("];");
1029 currentOffset = fieldOffset;
1030 }
1031 int alignment = memoryLayout.alignment(*fieldType);
1032 if (fieldOffset % alignment) {
1033 fErrors.error(parentOffset,
1034 "offset of field '" + field.fName + "' must be a multiple of " +
1035 to_string((int) alignment));
1036 }
1037 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001038 currentOffset += memoryLayout.size(*fieldType);
1039 std::vector<int> sizes;
1040 while (fieldType->kind() == Type::kArray_Kind) {
1041 sizes.push_back(fieldType->columns());
1042 fieldType = &fieldType->componentType();
1043 }
1044 this->writeModifiers(field.fModifiers, false);
1045 this->writeType(*fieldType);
1046 this->write(" ");
1047 this->writeName(field.fName);
1048 for (int s : sizes) {
1049 if (s <= 0) {
1050 this->write("[]");
1051 } else {
1052 this->write("[" + to_string(s) + "]");
1053 }
1054 }
1055 this->writeLine(";");
1056 if (parentIntf) {
1057 fInterfaceBlockMap[&field] = parentIntf;
1058 }
1059 }
1060}
1061
Ethan Nicholascc305772017-10-13 16:17:45 -04001062void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1063 this->writeExpression(value, kTopLevel_Precedence);
1064}
1065
Timothy Liang651286f2018-06-07 09:55:33 -04001066void MetalCodeGenerator::writeName(const String& name) {
1067 if (fReservedWords.find(name) != fReservedWords.end()) {
1068 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1069 }
1070 this->write(name);
1071}
1072
Ethan Nicholascc305772017-10-13 16:17:45 -04001073void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001074 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001075 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001076 for (const auto& stmt : decl.fVars) {
1077 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001078 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001079 continue;
1080 }
1081 if (wroteType) {
1082 this->write(", ");
1083 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001084 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001085 this->writeType(decl.fBaseType);
1086 this->write(" ");
1087 wroteType = true;
1088 }
Timothy Liang651286f2018-06-07 09:55:33 -04001089 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001090 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001091 this->write("[");
1092 if (size) {
1093 this->writeExpression(*size, kTopLevel_Precedence);
1094 }
1095 this->write("]");
1096 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001097 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001098 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001099 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001100 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001101 }
1102 if (wroteType) {
1103 this->write(";");
1104 }
1105}
1106
1107void MetalCodeGenerator::writeStatement(const Statement& s) {
1108 switch (s.fKind) {
1109 case Statement::kBlock_Kind:
1110 this->writeBlock((Block&) s);
1111 break;
1112 case Statement::kExpression_Kind:
1113 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1114 this->write(";");
1115 break;
1116 case Statement::kReturn_Kind:
1117 this->writeReturnStatement((ReturnStatement&) s);
1118 break;
1119 case Statement::kVarDeclarations_Kind:
1120 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1121 break;
1122 case Statement::kIf_Kind:
1123 this->writeIfStatement((IfStatement&) s);
1124 break;
1125 case Statement::kFor_Kind:
1126 this->writeForStatement((ForStatement&) s);
1127 break;
1128 case Statement::kWhile_Kind:
1129 this->writeWhileStatement((WhileStatement&) s);
1130 break;
1131 case Statement::kDo_Kind:
1132 this->writeDoStatement((DoStatement&) s);
1133 break;
1134 case Statement::kSwitch_Kind:
1135 this->writeSwitchStatement((SwitchStatement&) s);
1136 break;
1137 case Statement::kBreak_Kind:
1138 this->write("break;");
1139 break;
1140 case Statement::kContinue_Kind:
1141 this->write("continue;");
1142 break;
1143 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001144 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001145 break;
1146 case Statement::kNop_Kind:
1147 this->write(";");
1148 break;
1149 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001150#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001151 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001152#endif
1153 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001154 }
1155}
1156
1157void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1158 for (const auto& s : statements) {
1159 if (!s->isEmpty()) {
1160 this->writeStatement(*s);
1161 this->writeLine();
1162 }
1163 }
1164}
1165
1166void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001167 if (b.fIsScope) {
1168 this->writeLine("{");
1169 fIndentation++;
1170 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001171 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001172 if (b.fIsScope) {
1173 fIndentation--;
1174 this->write("}");
1175 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001176}
1177
1178void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1179 this->write("if (");
1180 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1181 this->write(") ");
1182 this->writeStatement(*stmt.fIfTrue);
1183 if (stmt.fIfFalse) {
1184 this->write(" else ");
1185 this->writeStatement(*stmt.fIfFalse);
1186 }
1187}
1188
1189void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1190 this->write("for (");
1191 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1192 this->writeStatement(*f.fInitializer);
1193 } else {
1194 this->write("; ");
1195 }
1196 if (f.fTest) {
1197 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1198 }
1199 this->write("; ");
1200 if (f.fNext) {
1201 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1202 }
1203 this->write(") ");
1204 this->writeStatement(*f.fStatement);
1205}
1206
1207void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1208 this->write("while (");
1209 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1210 this->write(") ");
1211 this->writeStatement(*w.fStatement);
1212}
1213
1214void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1215 this->write("do ");
1216 this->writeStatement(*d.fStatement);
1217 this->write(" while (");
1218 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1219 this->write(");");
1220}
1221
1222void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1223 this->write("switch (");
1224 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1225 this->writeLine(") {");
1226 fIndentation++;
1227 for (const auto& c : s.fCases) {
1228 if (c->fValue) {
1229 this->write("case ");
1230 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1231 this->writeLine(":");
1232 } else {
1233 this->writeLine("default:");
1234 }
1235 fIndentation++;
1236 for (const auto& stmt : c->fStatements) {
1237 this->writeStatement(*stmt);
1238 this->writeLine();
1239 }
1240 fIndentation--;
1241 }
1242 fIndentation--;
1243 this->write("}");
1244}
1245
1246void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1247 this->write("return");
1248 if (r.fExpression) {
1249 this->write(" ");
1250 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1251 }
1252 this->write(";");
1253}
1254
1255void MetalCodeGenerator::writeHeader() {
1256 this->write("#include <metal_stdlib>\n");
1257 this->write("#include <simd/simd.h>\n");
1258 this->write("using namespace metal;\n");
1259}
1260
1261void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001262 for (const auto& e : fProgram) {
1263 if (ProgramElement::kVar_Kind == e.fKind) {
1264 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001265 if (!decls.fVars.size()) {
1266 continue;
1267 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001268 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001269 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1270 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001271 if (-1 == fUniformBuffer) {
1272 this->write("struct Uniforms {\n");
1273 fUniformBuffer = first.fModifiers.fLayout.fSet;
1274 if (-1 == fUniformBuffer) {
1275 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1276 }
1277 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1278 if (-1 == fUniformBuffer) {
1279 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1280 "the same 'layout(set=...)'");
1281 }
1282 }
1283 this->write(" ");
1284 this->writeType(first.fType);
1285 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001286 for (const auto& stmt : decls.fVars) {
1287 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001288 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001289 }
1290 this->write(";\n");
1291 }
1292 }
1293 }
1294 if (-1 != fUniformBuffer) {
1295 this->write("};\n");
1296 }
1297}
1298
1299void MetalCodeGenerator::writeInputStruct() {
1300 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001301 for (const auto& e : fProgram) {
1302 if (ProgramElement::kVar_Kind == e.fKind) {
1303 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001304 if (!decls.fVars.size()) {
1305 continue;
1306 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001307 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001308 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1309 -1 == first.fModifiers.fLayout.fBuiltin) {
1310 this->write(" ");
1311 this->writeType(first.fType);
1312 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001313 for (const auto& stmt : decls.fVars) {
1314 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001315 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001316 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001317 if (fProgram.fKind == Program::kVertex_Kind) {
1318 this->write(" [[attribute(" +
1319 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1320 } else if (fProgram.fKind == Program::kFragment_Kind) {
1321 this->write(" [[user(locn" +
1322 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1323 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001324 }
1325 }
1326 this->write(";\n");
1327 }
1328 }
1329 }
1330 this->write("};\n");
1331}
1332
1333void MetalCodeGenerator::writeOutputStruct() {
1334 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001335 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001336 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001337 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001338 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001339 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001340 for (const auto& e : fProgram) {
1341 if (ProgramElement::kVar_Kind == e.fKind) {
1342 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001343 if (!decls.fVars.size()) {
1344 continue;
1345 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001346 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001347 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1348 -1 == first.fModifiers.fLayout.fBuiltin) {
1349 this->write(" ");
1350 this->writeType(first.fType);
1351 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001352 for (const auto& stmt : decls.fVars) {
1353 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001354 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001355 if (fProgram.fKind == Program::kVertex_Kind) {
1356 this->write(" [[user(locn" +
1357 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1358 } else if (fProgram.fKind == Program::kFragment_Kind) {
1359 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001360 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1361 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1362 if (colorIndex) {
1363 this->write(", index(" + to_string(colorIndex) + ")");
1364 }
1365 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001366 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001367 }
1368 this->write(";\n");
1369 }
1370 }
Timothy Liang7d637782018-06-05 09:58:07 -04001371 }
1372 if (fProgram.fKind == Program::kVertex_Kind) {
1373 this->write(" float sk_PointSize;\n");
1374 }
1375 this->write("};\n");
1376}
1377
1378void MetalCodeGenerator::writeInterfaceBlocks() {
1379 bool wroteInterfaceBlock = false;
1380 for (const auto& e : fProgram) {
1381 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1382 this->writeInterfaceBlock((InterfaceBlock&) e);
1383 wroteInterfaceBlock = true;
1384 }
1385 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001386 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001387 this->writeLine("struct sksl_synthetic_uniforms {");
1388 this->writeLine(" float u_skRTHeight;");
1389 this->writeLine("};");
1390 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001391}
1392
Timothy Liangee84fe12018-05-18 14:38:19 -04001393void MetalCodeGenerator::writeGlobalStruct() {
1394 bool wroteStructDecl = false;
Timothy Liang7d637782018-06-05 09:58:07 -04001395 for (const auto& intf : fInterfaceBlockNameMap) {
1396 if (!wroteStructDecl) {
1397 this->write("struct Globals {\n");
1398 wroteStructDecl = true;
1399 }
1400 fNeedsGlobalStructInit = true;
1401 const auto& intfType = intf.first;
1402 const auto& intfName = intf.second;
1403 this->write(" constant ");
1404 this->write(intfType->fTypeName);
1405 this->write("* ");
Timothy Liang651286f2018-06-07 09:55:33 -04001406 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -04001407 this->write(";\n");
1408 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001409 for (const auto& e : fProgram) {
1410 if (ProgramElement::kVar_Kind == e.fKind) {
1411 VarDeclarations& decls = (VarDeclarations&) e;
1412 if (!decls.fVars.size()) {
1413 continue;
1414 }
1415 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001416 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1417 first.fType.kind() == Type::kSampler_Kind) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001418 if (!wroteStructDecl) {
1419 this->write("struct Globals {\n");
1420 wroteStructDecl = true;
1421 }
1422 fNeedsGlobalStructInit = true;
1423 this->write(" ");
1424 this->writeType(first.fType);
1425 this->write(" ");
1426 for (const auto& stmt : decls.fVars) {
1427 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001428 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001429 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1430 fTextures.push_back(var.fVar);
1431 this->write(";\n");
1432 this->write(" sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -04001433 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001434 this->write(SAMPLER_SUFFIX);
1435 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001436 if (var.fValue) {
1437 fInitNonConstGlobalVars.push_back(&var);
1438 }
1439 }
1440 this->write(";\n");
1441 }
1442 }
1443 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001444 if (wroteStructDecl) {
1445 this->write("};\n");
1446 }
1447}
1448
Ethan Nicholascc305772017-10-13 16:17:45 -04001449void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1450 switch (e.fKind) {
1451 case ProgramElement::kExtension_Kind:
1452 break;
1453 case ProgramElement::kVar_Kind: {
1454 VarDeclarations& decl = (VarDeclarations&) e;
1455 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001456 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001457 if (-1 == builtin) {
1458 // normal var
1459 this->writeVarDeclarations(decl, true);
1460 this->writeLine();
1461 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1462 // ignore
1463 }
1464 }
1465 break;
1466 }
1467 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001468 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001469 break;
1470 case ProgramElement::kFunction_Kind:
1471 this->writeFunction((FunctionDefinition&) e);
1472 break;
1473 case ProgramElement::kModifiers_Kind:
1474 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1475 this->writeLine(";");
1476 break;
1477 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001478#ifdef SK_DEBUG
1479 ABORT("unsupported program element: %s\n", e.description().c_str());
1480#endif
1481 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001482 }
1483}
1484
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001485MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1486 if (!e) {
1487 return kNo_Requirements;
1488 }
1489 switch (e->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001490 case Expression::kFunctionCall_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001491 const FunctionCall& f = (const FunctionCall&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001492 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001493 for (const auto& arg : f.fArguments) {
1494 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001495 }
1496 return result;
1497 }
1498 case Expression::kConstructor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001499 const Constructor& c = (const Constructor&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001500 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001501 for (const auto& arg : c.fArguments) {
1502 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001503 }
1504 return result;
1505 }
Timothy Liang7d637782018-06-05 09:58:07 -04001506 case Expression::kFieldAccess_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001507 const FieldAccess& f = (const FieldAccess&) *e;
Timothy Liang7d637782018-06-05 09:58:07 -04001508 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1509 return kGlobals_Requirement;
1510 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001511 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001512 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001513 case Expression::kSwizzle_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001514 return this->requirements(((const Swizzle&) *e).fBase.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001515 case Expression::kBinary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001516 const BinaryExpression& b = (const BinaryExpression&) *e;
1517 return this->requirements(b.fLeft.get()) | this->requirements(b.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001518 }
1519 case Expression::kIndex_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001520 const IndexExpression& idx = (const IndexExpression&) *e;
1521 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001522 }
1523 case Expression::kPrefix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001524 return this->requirements(((const PrefixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001525 case Expression::kPostfix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001526 return this->requirements(((const PostfixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001527 case Expression::kTernary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001528 const TernaryExpression& t = (const TernaryExpression&) *e;
1529 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1530 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001531 }
1532 case Expression::kVariableReference_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001533 const VariableReference& v = (const VariableReference&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001534 Requirements result = kNo_Requirements;
1535 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001536 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001537 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1538 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1539 result = kInputs_Requirement;
1540 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1541 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001542 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1543 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001544 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001545 } else {
1546 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001547 }
1548 }
1549 return result;
1550 }
1551 default:
1552 return kNo_Requirements;
1553 }
1554}
1555
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001556MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1557 if (!s) {
1558 return kNo_Requirements;
1559 }
1560 switch (s->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001561 case Statement::kBlock_Kind: {
1562 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001563 for (const auto& child : ((const Block*) s)->fStatements) {
1564 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001565 }
1566 return result;
1567 }
Timothy Liang7d637782018-06-05 09:58:07 -04001568 case Statement::kVarDeclaration_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001569 const VarDeclaration& var = (const VarDeclaration&) *s;
1570 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001571 }
1572 case Statement::kVarDeclarations_Kind: {
1573 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001574 const VarDeclarations& decls = *((const VarDeclarationsStatement&) *s).fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001575 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001576 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001577 }
1578 return result;
1579 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001580 case Statement::kExpression_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001581 return this->requirements(((const ExpressionStatement&) *s).fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001582 case Statement::kReturn_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001583 const ReturnStatement& r = (const ReturnStatement&) *s;
1584 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001585 }
1586 case Statement::kIf_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001587 const IfStatement& i = (const IfStatement&) *s;
1588 return this->requirements(i.fTest.get()) |
1589 this->requirements(i.fIfTrue.get()) |
1590 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001591 }
1592 case Statement::kFor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001593 const ForStatement& f = (const ForStatement&) *s;
1594 return this->requirements(f.fInitializer.get()) |
1595 this->requirements(f.fTest.get()) |
1596 this->requirements(f.fNext.get()) |
1597 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001598 }
1599 case Statement::kWhile_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001600 const WhileStatement& w = (const WhileStatement&) *s;
1601 return this->requirements(w.fTest.get()) |
1602 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001603 }
1604 case Statement::kDo_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001605 const DoStatement& d = (const DoStatement&) *s;
1606 return this->requirements(d.fTest.get()) |
1607 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001608 }
1609 case Statement::kSwitch_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001610 const SwitchStatement& sw = (const SwitchStatement&) *s;
1611 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001612 for (const auto& c : sw.fCases) {
1613 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001614 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001615 }
1616 }
1617 return result;
1618 }
1619 default:
1620 return kNo_Requirements;
1621 }
1622}
1623
1624MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1625 if (f.fBuiltin) {
1626 return kNo_Requirements;
1627 }
1628 auto found = fRequirements.find(&f);
1629 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001630 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001631 for (const auto& e : fProgram) {
1632 if (ProgramElement::kFunction_Kind == e.fKind) {
1633 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001634 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001635 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001636 fRequirements[&f] = reqs;
1637 return reqs;
1638 }
1639 }
1640 }
1641 }
1642 return found->second;
1643}
1644
Timothy Liangb8eeb802018-07-23 16:46:16 -04001645bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001646 OutputStream* rawOut = fOut;
1647 fOut = &fHeader;
1648 fProgramKind = fProgram.fKind;
1649 this->writeHeader();
1650 this->writeUniformStruct();
1651 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001652 this->writeOutputStruct();
1653 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001654 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001655 StringStream body;
1656 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001657 for (const auto& e : fProgram) {
1658 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001659 }
1660 fOut = rawOut;
1661
1662 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001663 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001664 write_stringstream(body, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001665 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001666}
1667
1668}