blob: 21fb47f6ea947bd7fc82fbf1301a60b31576881e [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
John Stiles1bdafbf2020-05-28 12:17:20 -0400382// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
383// Keeps track of previously generated constructors so that we won't generate more than one
384// constructor for any given permutation of input argument types. Returns the name of the
385// generated constructor method.
386String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
387 const Type& matrix = c.fType;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500388 int columns = matrix.columns();
389 int rows = matrix.rows();
John Stiles1bdafbf2020-05-28 12:17:20 -0400390 const std::vector<std::unique_ptr<Expression>>& args = c.fArguments;
391
392 // Create the helper-method name and use it as our lookup key.
393 String name;
394 name.appendf("float%dx%d_from", columns, rows);
395 for (const std::unique_ptr<Expression>& expr : args) {
396 name.appendf("_%s", expr->fType.displayName().c_str());
397 }
398
399 // If a helper-method has already been synthesized, we don't need to synthesize it again.
400 auto [iter, newlyCreated] = fHelpers.insert(name);
401 if (!newlyCreated) {
402 return name;
403 }
404
405 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
406 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
407 // supply a mixture of scalars and vectors.)
408 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
409
410 size_t argIndex = 0;
411 const char* argSeparator = "";
412 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
413 fExtraFunctions.printf("%s%s x%zu", argSeparator,
414 expr->fType.displayName().c_str(), argIndex++);
415 argSeparator = ", ";
416 }
417
418 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
419
420 argIndex = 0;
421 int argPosition = 0;
422
423 const char* columnSeparator = "";
424 for (int c = 0; c < columns; ++c) {
425 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
426 columnSeparator = "), ";
427
428 const char* rowSeparator = "";
429 for (int r = 0; r < rows; ++r) {
430 fExtraFunctions.printf("%s", rowSeparator);
431 rowSeparator = ", ";
432
433 const Type& argType = args[argIndex]->fType;
434 switch (argType.kind()) {
435 case Type::kScalar_Kind: {
436 fExtraFunctions.printf("x%zu", argIndex);
437 break;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500438 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400439 case Type::kVector_Kind: {
440 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
441 break;
442 }
443 case Type::kMatrix_Kind: {
444 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
445 argPosition / argType.rows(),
446 argPosition % argType.rows());
447 break;
448 }
449 default: {
450 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
451 fExtraFunctions.printf("<error>");
452 break;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500453 }
454 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400455
456 ++argPosition;
457 if (argPosition >= argType.columns() * argType.rows()) {
458 ++argIndex;
459 argPosition = 0;
460 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500461 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400462 }
463
464 if (argPosition != 0 || argIndex != args.size()) {
465 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500466 name = "<error>";
467 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400468
469 fExtraFunctions.printf("));\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500470 return name;
471}
472
473bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
474 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
475 return false;
476 }
477 if (t1.columns() > 1) {
478 return this->canCoerce(t1.componentType(), t2.componentType());
479 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500480 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500481}
482
John Stiles1bdafbf2020-05-28 12:17:20 -0400483bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
484 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
485 if (c.fType.kind() != Type::kMatrix_Kind) {
486 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500487 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400488
489 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
490 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
491 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
492 // scalars can be constructed trivially. In more complex cases, we generate a helper function
493 // that converts our inputs into a properly-shaped matrix.
494 // A matrix construct helper method is always used if any input argument is a matrix.
495 // Helper methods are also necessary when any argument would span multiple rows. For instance:
496 //
497 // float2 x = (1, 2);
498 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
499 // | 2 4 6 |
500 //
501 // float2 x = (2, 3);
502 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
503 // | 2 4 6 |
504 //
505 // float4 x = (1, 2, 3, 4);
506 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
507 // | 2 4 |
508 //
509
510 int position = 0;
511 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
512 // If an input argument is a matrix, we need a helper function.
513 if (expr->fType.kind() == Type::kMatrix_Kind) {
514 return true;
515 }
516 position += expr->fType.columns();
517 if (position > c.fType.rows()) {
518 // An input argument would span multiple rows; a helper function is required.
519 return true;
520 }
521 if (position == c.fType.rows()) {
522 // We've advanced to the end of a row. Wrap to the start of the next row.
523 position = 0;
524 }
525 }
526
527 return false;
528}
529
530void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
531 // Handle special cases for single-argument constructors.
532 if (c.fArguments.size() == 1) {
533 // If the type is coercible, emit it directly.
534 const Expression& arg = *c.fArguments.front();
535 if (this->canCoerce(c.fType, arg.fType)) {
536 this->writeExpression(arg, parentPrecedence);
537 return;
538 }
539
540 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
541 // matrix constructor.
542 if (c.fType.kind() == Type::kMatrix_Kind && arg.fType.isNumber()) {
543 const Type& matrix = c.fType;
544 this->write("float");
545 this->write(to_string(matrix.columns()));
546 this->write("x");
547 this->write(to_string(matrix.rows()));
548 this->write("(");
549 this->writeExpression(arg, parentPrecedence);
550 this->write(")");
551 return;
552 }
553 }
554
555 // Emit and invoke a matrix-constructor helper method if one is necessary.
556 if (this->matrixConstructHelperIsNeeded(c)) {
557 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000558 this->write("(");
559 const char* separator = "";
John Stiles1bdafbf2020-05-28 12:17:20 -0400560 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
John Stiles1fa15b12020-05-28 17:36:54 +0000561 this->write(separator);
562 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400563 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400564 }
John Stiles1fa15b12020-05-28 17:36:54 +0000565 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400566 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400567 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400568
569 // Explicitly invoke the constructor, passing in the necessary arguments.
570 this->writeType(c.fType);
571 this->write("(");
572 const char* separator = "";
573 int scalarCount = 0;
574 for (const std::unique_ptr<Expression>& arg : c.fArguments) {
575 this->write(separator);
576 separator = ", ";
577 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() < c.fType.rows()) {
578 // Merge scalars and smaller vectors together.
579 if (!scalarCount) {
580 this->writeType(c.fType.componentType());
581 this->write(to_string(c.fType.rows()));
582 this->write("(");
583 }
584 scalarCount += arg->fType.columns();
585 }
586 this->writeExpression(*arg, kSequence_Precedence);
587 if (scalarCount && scalarCount == c.fType.rows()) {
588 this->write(")");
589 scalarCount = 0;
590 }
591 }
592 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400593}
594
595void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400596 if (fRTHeightName.length()) {
597 this->write("float4(_fragCoord.x, ");
598 this->write(fRTHeightName.c_str());
599 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500600 } else {
601 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
602 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400603}
604
605void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
606 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
607 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400608 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400609 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400610 case SK_FRAGCOORD_BUILTIN:
611 this->writeFragCoord();
612 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400613 case SK_VERTEXID_BUILTIN:
614 this->write("sk_VertexID");
615 break;
616 case SK_INSTANCEID_BUILTIN:
617 this->write("sk_InstanceID");
618 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400619 case SK_CLOCKWISE_BUILTIN:
620 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400621 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400622 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
623 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400624 default:
625 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
626 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
627 this->write("_in.");
628 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400629 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400630 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
631 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400632 this->write("_uniforms.");
633 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400634 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400635 }
636 }
Timothy Liang651286f2018-06-07 09:55:33 -0400637 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400638 }
639}
640
641void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
642 this->writeExpression(*expr.fBase, kPostfix_Precedence);
643 this->write("[");
644 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
645 this->write("]");
646}
647
648void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400649 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400650 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
651 this->writeExpression(*f.fBase, kPostfix_Precedence);
652 this->write(".");
653 }
Timothy Liang7d637782018-06-05 09:58:07 -0400654 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400655 case SK_CLIPDISTANCE_BUILTIN:
656 this->write("gl_ClipDistance");
657 break;
658 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400659 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400660 break;
661 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400662 if (field->fName == "sk_PointSize") {
663 this->write("_out->sk_PointSize");
664 } else {
665 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
666 this->write("_globals->");
667 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
668 this->write("->");
669 }
Timothy Liang651286f2018-06-07 09:55:33 -0400670 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400671 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400672 }
673}
674
675void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500676 int last = swizzle.fComponents.back();
677 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
678 this->writeType(swizzle.fType);
679 this->write("(");
680 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400681 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
682 this->write(".");
683 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500684 if (c >= 0) {
685 this->write(&("x\0y\0z\0w\0"[c * 2]));
686 }
687 }
688 if (last == SKSL_SWIZZLE_0) {
689 this->write(", 0)");
690 }
691 else if (last == SKSL_SWIZZLE_1) {
692 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400693 }
694}
695
696MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
697 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400698 case Token::Kind::TK_STAR: // fall through
699 case Token::Kind::TK_SLASH: // fall through
700 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
701 case Token::Kind::TK_PLUS: // fall through
702 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
703 case Token::Kind::TK_SHL: // fall through
704 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
705 case Token::Kind::TK_LT: // fall through
706 case Token::Kind::TK_GT: // fall through
707 case Token::Kind::TK_LTEQ: // fall through
708 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
709 case Token::Kind::TK_EQEQ: // fall through
710 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
711 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
712 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
713 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
714 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
715 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
716 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
717 case Token::Kind::TK_EQ: // fall through
718 case Token::Kind::TK_PLUSEQ: // fall through
719 case Token::Kind::TK_MINUSEQ: // fall through
720 case Token::Kind::TK_STAREQ: // fall through
721 case Token::Kind::TK_SLASHEQ: // fall through
722 case Token::Kind::TK_PERCENTEQ: // fall through
723 case Token::Kind::TK_SHLEQ: // fall through
724 case Token::Kind::TK_SHREQ: // fall through
725 case Token::Kind::TK_LOGICALANDEQ: // fall through
726 case Token::Kind::TK_LOGICALXOREQ: // fall through
727 case Token::Kind::TK_LOGICALOREQ: // fall through
728 case Token::Kind::TK_BITWISEANDEQ: // fall through
729 case Token::Kind::TK_BITWISEXOREQ: // fall through
730 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
731 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400732 default: ABORT("unsupported binary operator");
733 }
734}
735
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500736void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
737 const Type& result) {
738 String key = "TimesEqual" + left.name() + right.name();
739 if (fHelpers.find(key) == fHelpers.end()) {
740 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
741 " left = left * right;\n"
742 " return left;\n"
743 "}", result.name().c_str(), left.name().c_str(),
744 right.name().c_str());
745 }
746}
747
Ethan Nicholascc305772017-10-13 16:17:45 -0400748void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
749 Precedence parentPrecedence) {
750 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500751 bool needParens = precedence >= parentPrecedence;
752 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400753 case Token::Kind::TK_EQEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500754 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
755 this->write("all");
756 needParens = true;
757 }
758 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400759 case Token::Kind::TK_NEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500760 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400761 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500762 needParens = true;
763 }
764 break;
765 default:
766 break;
767 }
768 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400769 this->write("(");
770 }
771 if (Compiler::IsAssignment(b.fOperator) &&
772 Expression::kVariableReference_Kind == b.fLeft->fKind &&
773 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
774 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
775 // writing to an out parameter. Since we have to turn those into pointers, we have to
776 // dereference it here.
777 this->write("*");
778 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400779 if (b.fOperator == Token::Kind::TK_STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500780 b.fRight->fType.kind() == Type::kMatrix_Kind) {
781 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
782 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400783 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400784 if (b.fOperator != Token::Kind::TK_EQ && Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholascc305772017-10-13 16:17:45 -0400785 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
786 // This doesn't compile in Metal:
787 // float4 x = float4(1);
788 // x.xy *= float2x2(...);
789 // with the error message "non-const reference cannot bind to vector element",
790 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
791 // as long as the LHS has no side effects, and hope for the best otherwise.
792 this->write(" = ");
793 this->writeExpression(*b.fLeft, kAssignment_Precedence);
794 this->write(" ");
795 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400796 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400797 this->write(op.substr(0, op.size() - 1).c_str());
798 this->write(" ");
799 } else {
800 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
801 }
802 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500803 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400804 this->write(")");
805 }
806}
807
808void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
809 Precedence parentPrecedence) {
810 if (kTernary_Precedence >= parentPrecedence) {
811 this->write("(");
812 }
813 this->writeExpression(*t.fTest, kTernary_Precedence);
814 this->write(" ? ");
815 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
816 this->write(" : ");
817 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
818 if (kTernary_Precedence >= parentPrecedence) {
819 this->write(")");
820 }
821}
822
823void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
824 Precedence parentPrecedence) {
825 if (kPrefix_Precedence >= parentPrecedence) {
826 this->write("(");
827 }
828 this->write(Compiler::OperatorName(p.fOperator));
829 this->writeExpression(*p.fOperand, kPrefix_Precedence);
830 if (kPrefix_Precedence >= parentPrecedence) {
831 this->write(")");
832 }
833}
834
835void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
836 Precedence parentPrecedence) {
837 if (kPostfix_Precedence >= parentPrecedence) {
838 this->write("(");
839 }
840 this->writeExpression(*p.fOperand, kPostfix_Precedence);
841 this->write(Compiler::OperatorName(p.fOperator));
842 if (kPostfix_Precedence >= parentPrecedence) {
843 this->write(")");
844 }
845}
846
847void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
848 this->write(b.fValue ? "true" : "false");
849}
850
851void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
852 if (i.fType == *fContext.fUInt_Type) {
853 this->write(to_string(i.fValue & 0xffffffff) + "u");
854 } else {
855 this->write(to_string((int32_t) i.fValue));
856 }
857}
858
859void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
860 this->write(to_string(f.fValue));
861}
862
863void MetalCodeGenerator::writeSetting(const Setting& s) {
864 ABORT("internal error; setting was not folded to a constant during compilation\n");
865}
866
867void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400868 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400869 const char* separator = "";
870 if ("main" == f.fDeclaration.fName) {
871 switch (fProgram.fKind) {
872 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400873 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400874 break;
875 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400876 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400877 break;
878 default:
John Stilesf7d70432020-05-28 15:46:38 -0400879 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -0400880 }
881 this->write("(Inputs _in [[stage_in]]");
882 if (-1 != fUniformBuffer) {
883 this->write(", constant Uniforms& _uniforms [[buffer(" +
884 to_string(fUniformBuffer) + ")]]");
885 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400886 for (const auto& e : fProgram) {
887 if (ProgramElement::kVar_Kind == e.fKind) {
888 VarDeclarations& decls = (VarDeclarations&) e;
889 if (!decls.fVars.size()) {
890 continue;
891 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400892 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400893 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400894 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
Timothy Liang7d637782018-06-05 09:58:07 -0400895 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400896 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400897 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400898 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
899 this->write(")]]");
900 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400901 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400902 this->write(SAMPLER_SUFFIX);
903 this->write("[[sampler(");
904 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400905 this->write(")]]");
906 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400907 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400908 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
909 InterfaceBlock& intf = (InterfaceBlock&) e;
910 if ("sk_PerVertex" == intf.fTypeName) {
911 continue;
912 }
913 this->write(", constant ");
914 this->writeType(intf.fVariable.fType);
915 this->write("& " );
916 this->write(fInterfaceBlockNameMap[&intf]);
917 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400918 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400919 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400920 }
921 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500922 if (fProgram.fKind == Program::kFragment_Kind) {
923 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400924 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400925 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400926 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400927 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400928 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400929 } else if (fProgram.fKind == Program::kVertex_Kind) {
930 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400931 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400932 separator = ", ";
933 } else {
934 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400935 this->write(" ");
936 this->writeName(f.fDeclaration.fName);
937 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400938 Requirements requirements = this->requirements(f.fDeclaration);
939 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400940 this->write("Inputs _in");
941 separator = ", ";
942 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400943 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400944 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400945 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400946 separator = ", ";
947 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400948 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400949 this->write(separator);
950 this->write("Uniforms _uniforms");
951 separator = ", ";
952 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400953 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400954 this->write(separator);
955 this->write("thread Globals* _globals");
956 separator = ", ";
957 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400958 if (requirements & kFragCoord_Requirement) {
959 this->write(separator);
960 this->write("float4 _fragCoord");
961 separator = ", ";
962 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400963 }
964 for (const auto& param : f.fDeclaration.fParameters) {
965 this->write(separator);
966 separator = ", ";
967 this->writeModifiers(param->fModifiers, false);
968 std::vector<int> sizes;
969 const Type* type = &param->fType;
970 while (Type::kArray_Kind == type->kind()) {
971 sizes.push_back(type->columns());
972 type = &type->componentType();
973 }
974 this->writeType(*type);
975 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
976 this->write("*");
977 }
Timothy Liang651286f2018-06-07 09:55:33 -0400978 this->write(" ");
979 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400980 for (int s : sizes) {
981 if (s <= 0) {
982 this->write("[]");
983 } else {
984 this->write("[" + to_string(s) + "]");
985 }
986 }
987 }
988 this->writeLine(") {");
989
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400990 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -0400991
Ethan Nicholascc305772017-10-13 16:17:45 -0400992 if ("main" == f.fDeclaration.fName) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400993 if (fNeedsGlobalStructInit) {
John Stilesc67b3622020-05-28 17:53:13 -0400994 this->writeLine(" Globals globalStruct;");
995 for (const auto& [interfaceBlock, interfaceName] : fInterfaceBlockNameMap) {
996 this->write(" globalStruct.");
997 this->writeName(interfaceName);
998 this->write(" = &");
999 this->writeName(interfaceName);
1000 this->writeLine(";");
Timothy Liang7d637782018-06-05 09:58:07 -04001001 }
John Stilesc67b3622020-05-28 17:53:13 -04001002 for (const VarDeclaration* var : fInitNonConstGlobalVars) {
1003 this->write(" globalStruct.");
1004 this->writeName(var->fVar->fName);
1005 this->write(" = ");
Timothy Liangee84fe12018-05-18 14:38:19 -04001006 this->writeVarInitializer(*var->fVar, *var->fValue);
John Stilesc67b3622020-05-28 17:53:13 -04001007 this->writeLine(";");
Timothy Liangee84fe12018-05-18 14:38:19 -04001008 }
John Stilesc67b3622020-05-28 17:53:13 -04001009 for (const Variable* texture : fTextures) {
1010 this->write(" globalStruct.");
Timothy Liang651286f2018-06-07 09:55:33 -04001011 this->writeName(texture->fName);
John Stilesc67b3622020-05-28 17:53:13 -04001012 this->write(" = ");
Timothy Liang651286f2018-06-07 09:55:33 -04001013 this->writeName(texture->fName);
John Stilesc67b3622020-05-28 17:53:13 -04001014 this->writeLine(";");
1015
1016 String samplerName = String(texture->fName) + SAMPLER_SUFFIX;
1017 this->write(" globalStruct.");
1018 this->writeName(samplerName);
1019 this->write(" = ");
1020 this->writeName(samplerName);
1021 this->writeLine(";");
Timothy Liangee84fe12018-05-18 14:38:19 -04001022 }
Ethan Nicholasb47eb182019-12-20 10:49:41 -05001023 this->writeLine(" thread Globals* _globals = &globalStruct;");
1024 this->writeLine(" (void)_globals;");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001025 }
Timothy Liang7d637782018-06-05 09:58:07 -04001026 this->writeLine(" Outputs _outputStruct;");
1027 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001028 }
John Stilesc67b3622020-05-28 17:53:13 -04001029
Ethan Nicholascc305772017-10-13 16:17:45 -04001030 fFunctionHeader = "";
1031 OutputStream* oldOut = fOut;
1032 StringStream buffer;
1033 fOut = &buffer;
1034 fIndentation++;
1035 this->writeStatements(((Block&) *f.fBody).fStatements);
1036 if ("main" == f.fDeclaration.fName) {
1037 switch (fProgram.fKind) {
1038 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001039 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001040 break;
1041 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001042 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001043 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001044 break;
1045 default:
John Stilesf7d70432020-05-28 15:46:38 -04001046 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001047 }
1048 }
1049 fIndentation--;
1050 this->writeLine("}");
1051
1052 fOut = oldOut;
1053 this->write(fFunctionHeader);
1054 this->write(buffer.str());
1055}
1056
1057void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1058 bool globalContext) {
1059 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1060 this->write("thread ");
1061 }
1062 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001063 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001064 }
1065}
1066
1067void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1068 if ("sk_PerVertex" == intf.fTypeName) {
1069 return;
1070 }
1071 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001072 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001073 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001074 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001075 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -04001076 while (Type::kArray_Kind == structType->kind()) {
1077 structType = &structType->componentType();
1078 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001079 fIndentation++;
1080 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001081 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001082 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001083 }
1084 fIndentation--;
1085 this->write("}");
1086 if (intf.fInstanceName.size()) {
1087 this->write(" ");
1088 this->write(intf.fInstanceName);
1089 for (const auto& size : intf.fSizes) {
1090 this->write("[");
1091 if (size) {
1092 this->writeExpression(*size, kTopLevel_Precedence);
1093 }
1094 this->write("]");
1095 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001096 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1097 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001098 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001099 }
1100 this->writeLine(";");
1101}
1102
Timothy Liangdc89f192018-06-13 09:20:31 -04001103void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1104 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001105 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001106 int currentOffset = 0;
1107 for (const auto& field: fields) {
1108 int fieldOffset = field.fModifiers.fLayout.fOffset;
1109 const Type* fieldType = field.fType;
1110 if (fieldOffset != -1) {
1111 if (currentOffset > fieldOffset) {
1112 fErrors.error(parentOffset,
1113 "offset of field '" + field.fName + "' must be at least " +
1114 to_string((int) currentOffset));
1115 } else if (currentOffset < fieldOffset) {
1116 this->write("char pad");
1117 this->write(to_string(fPaddingCount++));
1118 this->write("[");
1119 this->write(to_string(fieldOffset - currentOffset));
1120 this->writeLine("];");
1121 currentOffset = fieldOffset;
1122 }
1123 int alignment = memoryLayout.alignment(*fieldType);
1124 if (fieldOffset % alignment) {
1125 fErrors.error(parentOffset,
1126 "offset of field '" + field.fName + "' must be a multiple of " +
1127 to_string((int) alignment));
1128 }
1129 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001130 currentOffset += memoryLayout.size(*fieldType);
1131 std::vector<int> sizes;
1132 while (fieldType->kind() == Type::kArray_Kind) {
1133 sizes.push_back(fieldType->columns());
1134 fieldType = &fieldType->componentType();
1135 }
1136 this->writeModifiers(field.fModifiers, false);
1137 this->writeType(*fieldType);
1138 this->write(" ");
1139 this->writeName(field.fName);
1140 for (int s : sizes) {
1141 if (s <= 0) {
1142 this->write("[]");
1143 } else {
1144 this->write("[" + to_string(s) + "]");
1145 }
1146 }
1147 this->writeLine(";");
1148 if (parentIntf) {
1149 fInterfaceBlockMap[&field] = parentIntf;
1150 }
1151 }
1152}
1153
Ethan Nicholascc305772017-10-13 16:17:45 -04001154void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1155 this->writeExpression(value, kTopLevel_Precedence);
1156}
1157
Timothy Liang651286f2018-06-07 09:55:33 -04001158void MetalCodeGenerator::writeName(const String& name) {
1159 if (fReservedWords.find(name) != fReservedWords.end()) {
1160 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1161 }
1162 this->write(name);
1163}
1164
Ethan Nicholascc305772017-10-13 16:17:45 -04001165void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001166 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001167 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001168 for (const auto& stmt : decl.fVars) {
1169 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001170 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001171 continue;
1172 }
1173 if (wroteType) {
1174 this->write(", ");
1175 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001176 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001177 this->writeType(decl.fBaseType);
1178 this->write(" ");
1179 wroteType = true;
1180 }
Timothy Liang651286f2018-06-07 09:55:33 -04001181 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001182 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001183 this->write("[");
1184 if (size) {
1185 this->writeExpression(*size, kTopLevel_Precedence);
1186 }
1187 this->write("]");
1188 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001189 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001190 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001191 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001192 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001193 }
1194 if (wroteType) {
1195 this->write(";");
1196 }
1197}
1198
1199void MetalCodeGenerator::writeStatement(const Statement& s) {
1200 switch (s.fKind) {
1201 case Statement::kBlock_Kind:
1202 this->writeBlock((Block&) s);
1203 break;
1204 case Statement::kExpression_Kind:
1205 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1206 this->write(";");
1207 break;
1208 case Statement::kReturn_Kind:
1209 this->writeReturnStatement((ReturnStatement&) s);
1210 break;
1211 case Statement::kVarDeclarations_Kind:
1212 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1213 break;
1214 case Statement::kIf_Kind:
1215 this->writeIfStatement((IfStatement&) s);
1216 break;
1217 case Statement::kFor_Kind:
1218 this->writeForStatement((ForStatement&) s);
1219 break;
1220 case Statement::kWhile_Kind:
1221 this->writeWhileStatement((WhileStatement&) s);
1222 break;
1223 case Statement::kDo_Kind:
1224 this->writeDoStatement((DoStatement&) s);
1225 break;
1226 case Statement::kSwitch_Kind:
1227 this->writeSwitchStatement((SwitchStatement&) s);
1228 break;
1229 case Statement::kBreak_Kind:
1230 this->write("break;");
1231 break;
1232 case Statement::kContinue_Kind:
1233 this->write("continue;");
1234 break;
1235 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001236 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001237 break;
1238 case Statement::kNop_Kind:
1239 this->write(";");
1240 break;
1241 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001242#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001243 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001244#endif
1245 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001246 }
1247}
1248
1249void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1250 for (const auto& s : statements) {
1251 if (!s->isEmpty()) {
1252 this->writeStatement(*s);
1253 this->writeLine();
1254 }
1255 }
1256}
1257
1258void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001259 if (b.fIsScope) {
1260 this->writeLine("{");
1261 fIndentation++;
1262 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001263 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001264 if (b.fIsScope) {
1265 fIndentation--;
1266 this->write("}");
1267 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001268}
1269
1270void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1271 this->write("if (");
1272 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1273 this->write(") ");
1274 this->writeStatement(*stmt.fIfTrue);
1275 if (stmt.fIfFalse) {
1276 this->write(" else ");
1277 this->writeStatement(*stmt.fIfFalse);
1278 }
1279}
1280
1281void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1282 this->write("for (");
1283 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1284 this->writeStatement(*f.fInitializer);
1285 } else {
1286 this->write("; ");
1287 }
1288 if (f.fTest) {
1289 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1290 }
1291 this->write("; ");
1292 if (f.fNext) {
1293 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1294 }
1295 this->write(") ");
1296 this->writeStatement(*f.fStatement);
1297}
1298
1299void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1300 this->write("while (");
1301 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1302 this->write(") ");
1303 this->writeStatement(*w.fStatement);
1304}
1305
1306void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1307 this->write("do ");
1308 this->writeStatement(*d.fStatement);
1309 this->write(" while (");
1310 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1311 this->write(");");
1312}
1313
1314void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1315 this->write("switch (");
1316 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1317 this->writeLine(") {");
1318 fIndentation++;
1319 for (const auto& c : s.fCases) {
1320 if (c->fValue) {
1321 this->write("case ");
1322 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1323 this->writeLine(":");
1324 } else {
1325 this->writeLine("default:");
1326 }
1327 fIndentation++;
1328 for (const auto& stmt : c->fStatements) {
1329 this->writeStatement(*stmt);
1330 this->writeLine();
1331 }
1332 fIndentation--;
1333 }
1334 fIndentation--;
1335 this->write("}");
1336}
1337
1338void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1339 this->write("return");
1340 if (r.fExpression) {
1341 this->write(" ");
1342 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1343 }
1344 this->write(";");
1345}
1346
1347void MetalCodeGenerator::writeHeader() {
1348 this->write("#include <metal_stdlib>\n");
1349 this->write("#include <simd/simd.h>\n");
1350 this->write("using namespace metal;\n");
1351}
1352
1353void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001354 for (const auto& e : fProgram) {
1355 if (ProgramElement::kVar_Kind == e.fKind) {
1356 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001357 if (!decls.fVars.size()) {
1358 continue;
1359 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001360 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001361 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1362 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001363 if (-1 == fUniformBuffer) {
1364 this->write("struct Uniforms {\n");
1365 fUniformBuffer = first.fModifiers.fLayout.fSet;
1366 if (-1 == fUniformBuffer) {
1367 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1368 }
1369 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1370 if (-1 == fUniformBuffer) {
1371 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1372 "the same 'layout(set=...)'");
1373 }
1374 }
1375 this->write(" ");
1376 this->writeType(first.fType);
1377 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001378 for (const auto& stmt : decls.fVars) {
1379 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001380 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001381 }
1382 this->write(";\n");
1383 }
1384 }
1385 }
1386 if (-1 != fUniformBuffer) {
1387 this->write("};\n");
1388 }
1389}
1390
1391void MetalCodeGenerator::writeInputStruct() {
1392 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001393 for (const auto& e : fProgram) {
1394 if (ProgramElement::kVar_Kind == e.fKind) {
1395 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001396 if (!decls.fVars.size()) {
1397 continue;
1398 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001399 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001400 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1401 -1 == first.fModifiers.fLayout.fBuiltin) {
1402 this->write(" ");
1403 this->writeType(first.fType);
1404 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001405 for (const auto& stmt : decls.fVars) {
1406 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001407 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001408 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001409 if (fProgram.fKind == Program::kVertex_Kind) {
1410 this->write(" [[attribute(" +
1411 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1412 } else if (fProgram.fKind == Program::kFragment_Kind) {
1413 this->write(" [[user(locn" +
1414 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1415 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001416 }
1417 }
1418 this->write(";\n");
1419 }
1420 }
1421 }
1422 this->write("};\n");
1423}
1424
1425void MetalCodeGenerator::writeOutputStruct() {
1426 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001427 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001428 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001429 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001430 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001431 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001432 for (const auto& e : fProgram) {
1433 if (ProgramElement::kVar_Kind == e.fKind) {
1434 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001435 if (!decls.fVars.size()) {
1436 continue;
1437 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001438 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1440 -1 == first.fModifiers.fLayout.fBuiltin) {
1441 this->write(" ");
1442 this->writeType(first.fType);
1443 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001444 for (const auto& stmt : decls.fVars) {
1445 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001446 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001447 if (fProgram.fKind == Program::kVertex_Kind) {
1448 this->write(" [[user(locn" +
1449 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1450 } else if (fProgram.fKind == Program::kFragment_Kind) {
1451 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001452 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1453 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1454 if (colorIndex) {
1455 this->write(", index(" + to_string(colorIndex) + ")");
1456 }
1457 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001458 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001459 }
1460 this->write(";\n");
1461 }
1462 }
Timothy Liang7d637782018-06-05 09:58:07 -04001463 }
1464 if (fProgram.fKind == Program::kVertex_Kind) {
1465 this->write(" float sk_PointSize;\n");
1466 }
1467 this->write("};\n");
1468}
1469
1470void MetalCodeGenerator::writeInterfaceBlocks() {
1471 bool wroteInterfaceBlock = false;
1472 for (const auto& e : fProgram) {
1473 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1474 this->writeInterfaceBlock((InterfaceBlock&) e);
1475 wroteInterfaceBlock = true;
1476 }
1477 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001478 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001479 this->writeLine("struct sksl_synthetic_uniforms {");
1480 this->writeLine(" float u_skRTHeight;");
1481 this->writeLine("};");
1482 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001483}
1484
Timothy Liangee84fe12018-05-18 14:38:19 -04001485void MetalCodeGenerator::writeGlobalStruct() {
1486 bool wroteStructDecl = false;
John Stilesc67b3622020-05-28 17:53:13 -04001487 auto WriteStructDecl = [&] {
Timothy Liang7d637782018-06-05 09:58:07 -04001488 if (!wroteStructDecl) {
1489 this->write("struct Globals {\n");
1490 wroteStructDecl = true;
1491 }
John Stilesc67b3622020-05-28 17:53:13 -04001492 };
1493
1494 for (const auto& intf : fInterfaceBlockNameMap) {
1495 WriteStructDecl();
Timothy Liang7d637782018-06-05 09:58:07 -04001496 fNeedsGlobalStructInit = true;
1497 const auto& intfType = intf.first;
1498 const auto& intfName = intf.second;
1499 this->write(" constant ");
1500 this->write(intfType->fTypeName);
1501 this->write("* ");
Timothy Liang651286f2018-06-07 09:55:33 -04001502 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -04001503 this->write(";\n");
1504 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001505 for (const auto& e : fProgram) {
1506 if (ProgramElement::kVar_Kind == e.fKind) {
1507 VarDeclarations& decls = (VarDeclarations&) e;
1508 if (!decls.fVars.size()) {
1509 continue;
1510 }
1511 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001512 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1513 first.fType.kind() == Type::kSampler_Kind) {
John Stilesc67b3622020-05-28 17:53:13 -04001514 WriteStructDecl();
Timothy Liangee84fe12018-05-18 14:38:19 -04001515 fNeedsGlobalStructInit = true;
1516 this->write(" ");
1517 this->writeType(first.fType);
1518 this->write(" ");
1519 for (const auto& stmt : decls.fVars) {
1520 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001521 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001522 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1523 fTextures.push_back(var.fVar);
1524 this->write(";\n");
1525 this->write(" sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -04001526 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001527 this->write(SAMPLER_SUFFIX);
1528 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001529 if (var.fValue) {
1530 fInitNonConstGlobalVars.push_back(&var);
1531 }
1532 }
1533 this->write(";\n");
1534 }
1535 }
1536 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001537 if (wroteStructDecl) {
1538 this->write("};\n");
1539 }
1540}
1541
Ethan Nicholascc305772017-10-13 16:17:45 -04001542void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1543 switch (e.fKind) {
1544 case ProgramElement::kExtension_Kind:
1545 break;
1546 case ProgramElement::kVar_Kind: {
1547 VarDeclarations& decl = (VarDeclarations&) e;
1548 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001549 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001550 if (-1 == builtin) {
1551 // normal var
1552 this->writeVarDeclarations(decl, true);
1553 this->writeLine();
1554 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1555 // ignore
1556 }
1557 }
1558 break;
1559 }
1560 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001561 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001562 break;
1563 case ProgramElement::kFunction_Kind:
1564 this->writeFunction((FunctionDefinition&) e);
1565 break;
1566 case ProgramElement::kModifiers_Kind:
1567 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1568 this->writeLine(";");
1569 break;
1570 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001571#ifdef SK_DEBUG
1572 ABORT("unsupported program element: %s\n", e.description().c_str());
1573#endif
1574 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001575 }
1576}
1577
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001578MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1579 if (!e) {
1580 return kNo_Requirements;
1581 }
1582 switch (e->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001583 case Expression::kFunctionCall_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001584 const FunctionCall& f = (const FunctionCall&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001585 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001586 for (const auto& arg : f.fArguments) {
1587 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001588 }
1589 return result;
1590 }
1591 case Expression::kConstructor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001592 const Constructor& c = (const Constructor&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001593 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001594 for (const auto& arg : c.fArguments) {
1595 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001596 }
1597 return result;
1598 }
Timothy Liang7d637782018-06-05 09:58:07 -04001599 case Expression::kFieldAccess_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001600 const FieldAccess& f = (const FieldAccess&) *e;
Timothy Liang7d637782018-06-05 09:58:07 -04001601 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1602 return kGlobals_Requirement;
1603 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001604 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001605 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001606 case Expression::kSwizzle_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001607 return this->requirements(((const Swizzle&) *e).fBase.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001608 case Expression::kBinary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001609 const BinaryExpression& b = (const BinaryExpression&) *e;
1610 return this->requirements(b.fLeft.get()) | this->requirements(b.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001611 }
1612 case Expression::kIndex_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001613 const IndexExpression& idx = (const IndexExpression&) *e;
1614 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001615 }
1616 case Expression::kPrefix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001617 return this->requirements(((const PrefixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001618 case Expression::kPostfix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001619 return this->requirements(((const PostfixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001620 case Expression::kTernary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001621 const TernaryExpression& t = (const TernaryExpression&) *e;
1622 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1623 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001624 }
1625 case Expression::kVariableReference_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001626 const VariableReference& v = (const VariableReference&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001627 Requirements result = kNo_Requirements;
1628 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001629 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001630 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1631 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1632 result = kInputs_Requirement;
1633 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1634 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001635 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1636 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001637 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001638 } else {
1639 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001640 }
1641 }
1642 return result;
1643 }
1644 default:
1645 return kNo_Requirements;
1646 }
1647}
1648
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001649MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1650 if (!s) {
1651 return kNo_Requirements;
1652 }
1653 switch (s->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001654 case Statement::kBlock_Kind: {
1655 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001656 for (const auto& child : ((const Block*) s)->fStatements) {
1657 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001658 }
1659 return result;
1660 }
Timothy Liang7d637782018-06-05 09:58:07 -04001661 case Statement::kVarDeclaration_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001662 const VarDeclaration& var = (const VarDeclaration&) *s;
1663 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001664 }
1665 case Statement::kVarDeclarations_Kind: {
1666 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001667 const VarDeclarations& decls = *((const VarDeclarationsStatement&) *s).fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001668 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001669 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001670 }
1671 return result;
1672 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001673 case Statement::kExpression_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001674 return this->requirements(((const ExpressionStatement&) *s).fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001675 case Statement::kReturn_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001676 const ReturnStatement& r = (const ReturnStatement&) *s;
1677 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 }
1679 case Statement::kIf_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001680 const IfStatement& i = (const IfStatement&) *s;
1681 return this->requirements(i.fTest.get()) |
1682 this->requirements(i.fIfTrue.get()) |
1683 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001684 }
1685 case Statement::kFor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001686 const ForStatement& f = (const ForStatement&) *s;
1687 return this->requirements(f.fInitializer.get()) |
1688 this->requirements(f.fTest.get()) |
1689 this->requirements(f.fNext.get()) |
1690 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001691 }
1692 case Statement::kWhile_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001693 const WhileStatement& w = (const WhileStatement&) *s;
1694 return this->requirements(w.fTest.get()) |
1695 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001696 }
1697 case Statement::kDo_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001698 const DoStatement& d = (const DoStatement&) *s;
1699 return this->requirements(d.fTest.get()) |
1700 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001701 }
1702 case Statement::kSwitch_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001703 const SwitchStatement& sw = (const SwitchStatement&) *s;
1704 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001705 for (const auto& c : sw.fCases) {
1706 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001707 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001708 }
1709 }
1710 return result;
1711 }
1712 default:
1713 return kNo_Requirements;
1714 }
1715}
1716
1717MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1718 if (f.fBuiltin) {
1719 return kNo_Requirements;
1720 }
1721 auto found = fRequirements.find(&f);
1722 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001723 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001724 for (const auto& e : fProgram) {
1725 if (ProgramElement::kFunction_Kind == e.fKind) {
1726 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001727 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001728 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001729 fRequirements[&f] = reqs;
1730 return reqs;
1731 }
1732 }
1733 }
1734 }
1735 return found->second;
1736}
1737
Timothy Liangb8eeb802018-07-23 16:46:16 -04001738bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001739 OutputStream* rawOut = fOut;
1740 fOut = &fHeader;
1741 fProgramKind = fProgram.fKind;
1742 this->writeHeader();
1743 this->writeUniformStruct();
1744 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001745 this->writeOutputStruct();
1746 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001747 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001748 StringStream body;
1749 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001750 for (const auto& e : fProgram) {
1751 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001752 }
1753 fOut = rawOut;
1754
1755 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001756 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001757 write_stringstream(body, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001758 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001759}
1760
1761}