blob: e518a13e0dd2420cf9611bcc1775d39aa904644c [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) {
John Stiles08cb2c12020-07-06 10:18:49 -0400895 if (var.fVar->fModifiers.fLayout.fBinding < 0) {
896 fErrors.error(decls.fOffset,
897 "Metal samplers must have 'layout(binding=...)'");
898 }
Timothy Liang7d637782018-06-05 09:58:07 -0400899 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400900 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400901 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400902 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
903 this->write(")]]");
904 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400905 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400906 this->write(SAMPLER_SUFFIX);
907 this->write("[[sampler(");
908 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400909 this->write(")]]");
910 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400911 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400912 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
913 InterfaceBlock& intf = (InterfaceBlock&) e;
914 if ("sk_PerVertex" == intf.fTypeName) {
915 continue;
916 }
917 this->write(", constant ");
918 this->writeType(intf.fVariable.fType);
919 this->write("& " );
920 this->write(fInterfaceBlockNameMap[&intf]);
921 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400922 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400923 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400924 }
925 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500926 if (fProgram.fKind == Program::kFragment_Kind) {
927 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400928 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400929 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400930 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400931 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400932 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400933 } else if (fProgram.fKind == Program::kVertex_Kind) {
934 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400935 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400936 separator = ", ";
937 } else {
938 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400939 this->write(" ");
940 this->writeName(f.fDeclaration.fName);
941 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400942 Requirements requirements = this->requirements(f.fDeclaration);
943 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400944 this->write("Inputs _in");
945 separator = ", ";
946 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400947 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400948 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400949 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400950 separator = ", ";
951 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400952 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400953 this->write(separator);
954 this->write("Uniforms _uniforms");
955 separator = ", ";
956 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400957 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400958 this->write(separator);
959 this->write("thread Globals* _globals");
960 separator = ", ";
961 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400962 if (requirements & kFragCoord_Requirement) {
963 this->write(separator);
964 this->write("float4 _fragCoord");
965 separator = ", ";
966 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400967 }
968 for (const auto& param : f.fDeclaration.fParameters) {
969 this->write(separator);
970 separator = ", ";
971 this->writeModifiers(param->fModifiers, false);
972 std::vector<int> sizes;
973 const Type* type = &param->fType;
974 while (Type::kArray_Kind == type->kind()) {
975 sizes.push_back(type->columns());
976 type = &type->componentType();
977 }
978 this->writeType(*type);
979 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
980 this->write("*");
981 }
Timothy Liang651286f2018-06-07 09:55:33 -0400982 this->write(" ");
983 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400984 for (int s : sizes) {
985 if (s <= 0) {
986 this->write("[]");
987 } else {
988 this->write("[" + to_string(s) + "]");
989 }
990 }
991 }
992 this->writeLine(") {");
993
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400994 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -0400995
Ethan Nicholascc305772017-10-13 16:17:45 -0400996 if ("main" == f.fDeclaration.fName) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400997 if (fNeedsGlobalStructInit) {
John Stilesc67b3622020-05-28 17:53:13 -0400998 this->writeLine(" Globals globalStruct;");
999 for (const auto& [interfaceBlock, interfaceName] : fInterfaceBlockNameMap) {
1000 this->write(" globalStruct.");
1001 this->writeName(interfaceName);
1002 this->write(" = &");
1003 this->writeName(interfaceName);
1004 this->writeLine(";");
Timothy Liang7d637782018-06-05 09:58:07 -04001005 }
John Stilesc67b3622020-05-28 17:53:13 -04001006 for (const VarDeclaration* var : fInitNonConstGlobalVars) {
1007 this->write(" globalStruct.");
1008 this->writeName(var->fVar->fName);
1009 this->write(" = ");
Timothy Liangee84fe12018-05-18 14:38:19 -04001010 this->writeVarInitializer(*var->fVar, *var->fValue);
John Stilesc67b3622020-05-28 17:53:13 -04001011 this->writeLine(";");
Timothy Liangee84fe12018-05-18 14:38:19 -04001012 }
John Stilesc67b3622020-05-28 17:53:13 -04001013 for (const Variable* texture : fTextures) {
1014 this->write(" globalStruct.");
Timothy Liang651286f2018-06-07 09:55:33 -04001015 this->writeName(texture->fName);
John Stilesc67b3622020-05-28 17:53:13 -04001016 this->write(" = ");
Timothy Liang651286f2018-06-07 09:55:33 -04001017 this->writeName(texture->fName);
John Stilesc67b3622020-05-28 17:53:13 -04001018 this->writeLine(";");
1019
1020 String samplerName = String(texture->fName) + SAMPLER_SUFFIX;
1021 this->write(" globalStruct.");
1022 this->writeName(samplerName);
1023 this->write(" = ");
1024 this->writeName(samplerName);
1025 this->writeLine(";");
Timothy Liangee84fe12018-05-18 14:38:19 -04001026 }
Ethan Nicholasb47eb182019-12-20 10:49:41 -05001027 this->writeLine(" thread Globals* _globals = &globalStruct;");
1028 this->writeLine(" (void)_globals;");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001029 }
Timothy Liang7d637782018-06-05 09:58:07 -04001030 this->writeLine(" Outputs _outputStruct;");
1031 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001032 }
John Stilesc67b3622020-05-28 17:53:13 -04001033
Ethan Nicholascc305772017-10-13 16:17:45 -04001034 fFunctionHeader = "";
1035 OutputStream* oldOut = fOut;
1036 StringStream buffer;
1037 fOut = &buffer;
1038 fIndentation++;
1039 this->writeStatements(((Block&) *f.fBody).fStatements);
1040 if ("main" == f.fDeclaration.fName) {
1041 switch (fProgram.fKind) {
1042 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001043 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001044 break;
1045 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001046 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001047 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001048 break;
1049 default:
John Stilesf7d70432020-05-28 15:46:38 -04001050 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001051 }
1052 }
1053 fIndentation--;
1054 this->writeLine("}");
1055
1056 fOut = oldOut;
1057 this->write(fFunctionHeader);
1058 this->write(buffer.str());
1059}
1060
1061void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1062 bool globalContext) {
1063 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1064 this->write("thread ");
1065 }
1066 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001067 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001068 }
1069}
1070
1071void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1072 if ("sk_PerVertex" == intf.fTypeName) {
1073 return;
1074 }
1075 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001076 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001077 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001078 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001079 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -04001080 while (Type::kArray_Kind == structType->kind()) {
1081 structType = &structType->componentType();
1082 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001083 fIndentation++;
1084 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001085 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001086 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001087 }
1088 fIndentation--;
1089 this->write("}");
1090 if (intf.fInstanceName.size()) {
1091 this->write(" ");
1092 this->write(intf.fInstanceName);
1093 for (const auto& size : intf.fSizes) {
1094 this->write("[");
1095 if (size) {
1096 this->writeExpression(*size, kTopLevel_Precedence);
1097 }
1098 this->write("]");
1099 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001100 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1101 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001102 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001103 }
1104 this->writeLine(";");
1105}
1106
Timothy Liangdc89f192018-06-13 09:20:31 -04001107void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1108 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001109 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001110 int currentOffset = 0;
1111 for (const auto& field: fields) {
1112 int fieldOffset = field.fModifiers.fLayout.fOffset;
1113 const Type* fieldType = field.fType;
1114 if (fieldOffset != -1) {
1115 if (currentOffset > fieldOffset) {
1116 fErrors.error(parentOffset,
1117 "offset of field '" + field.fName + "' must be at least " +
1118 to_string((int) currentOffset));
1119 } else if (currentOffset < fieldOffset) {
1120 this->write("char pad");
1121 this->write(to_string(fPaddingCount++));
1122 this->write("[");
1123 this->write(to_string(fieldOffset - currentOffset));
1124 this->writeLine("];");
1125 currentOffset = fieldOffset;
1126 }
1127 int alignment = memoryLayout.alignment(*fieldType);
1128 if (fieldOffset % alignment) {
1129 fErrors.error(parentOffset,
1130 "offset of field '" + field.fName + "' must be a multiple of " +
1131 to_string((int) alignment));
1132 }
1133 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001134 currentOffset += memoryLayout.size(*fieldType);
1135 std::vector<int> sizes;
1136 while (fieldType->kind() == Type::kArray_Kind) {
1137 sizes.push_back(fieldType->columns());
1138 fieldType = &fieldType->componentType();
1139 }
1140 this->writeModifiers(field.fModifiers, false);
1141 this->writeType(*fieldType);
1142 this->write(" ");
1143 this->writeName(field.fName);
1144 for (int s : sizes) {
1145 if (s <= 0) {
1146 this->write("[]");
1147 } else {
1148 this->write("[" + to_string(s) + "]");
1149 }
1150 }
1151 this->writeLine(";");
1152 if (parentIntf) {
1153 fInterfaceBlockMap[&field] = parentIntf;
1154 }
1155 }
1156}
1157
Ethan Nicholascc305772017-10-13 16:17:45 -04001158void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1159 this->writeExpression(value, kTopLevel_Precedence);
1160}
1161
Timothy Liang651286f2018-06-07 09:55:33 -04001162void MetalCodeGenerator::writeName(const String& name) {
1163 if (fReservedWords.find(name) != fReservedWords.end()) {
1164 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1165 }
1166 this->write(name);
1167}
1168
Ethan Nicholascc305772017-10-13 16:17:45 -04001169void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001170 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001171 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001172 for (const auto& stmt : decl.fVars) {
1173 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001174 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001175 continue;
1176 }
1177 if (wroteType) {
1178 this->write(", ");
1179 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001180 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001181 this->writeType(decl.fBaseType);
1182 this->write(" ");
1183 wroteType = true;
1184 }
Timothy Liang651286f2018-06-07 09:55:33 -04001185 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001186 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001187 this->write("[");
1188 if (size) {
1189 this->writeExpression(*size, kTopLevel_Precedence);
1190 }
1191 this->write("]");
1192 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001193 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001194 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001195 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001196 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001197 }
1198 if (wroteType) {
1199 this->write(";");
1200 }
1201}
1202
1203void MetalCodeGenerator::writeStatement(const Statement& s) {
1204 switch (s.fKind) {
1205 case Statement::kBlock_Kind:
1206 this->writeBlock((Block&) s);
1207 break;
1208 case Statement::kExpression_Kind:
1209 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1210 this->write(";");
1211 break;
1212 case Statement::kReturn_Kind:
1213 this->writeReturnStatement((ReturnStatement&) s);
1214 break;
1215 case Statement::kVarDeclarations_Kind:
1216 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1217 break;
1218 case Statement::kIf_Kind:
1219 this->writeIfStatement((IfStatement&) s);
1220 break;
1221 case Statement::kFor_Kind:
1222 this->writeForStatement((ForStatement&) s);
1223 break;
1224 case Statement::kWhile_Kind:
1225 this->writeWhileStatement((WhileStatement&) s);
1226 break;
1227 case Statement::kDo_Kind:
1228 this->writeDoStatement((DoStatement&) s);
1229 break;
1230 case Statement::kSwitch_Kind:
1231 this->writeSwitchStatement((SwitchStatement&) s);
1232 break;
1233 case Statement::kBreak_Kind:
1234 this->write("break;");
1235 break;
1236 case Statement::kContinue_Kind:
1237 this->write("continue;");
1238 break;
1239 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001240 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001241 break;
1242 case Statement::kNop_Kind:
1243 this->write(";");
1244 break;
1245 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001246#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001247 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001248#endif
1249 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001250 }
1251}
1252
1253void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1254 for (const auto& s : statements) {
1255 if (!s->isEmpty()) {
1256 this->writeStatement(*s);
1257 this->writeLine();
1258 }
1259 }
1260}
1261
1262void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001263 if (b.fIsScope) {
1264 this->writeLine("{");
1265 fIndentation++;
1266 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001267 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001268 if (b.fIsScope) {
1269 fIndentation--;
1270 this->write("}");
1271 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001272}
1273
1274void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1275 this->write("if (");
1276 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1277 this->write(") ");
1278 this->writeStatement(*stmt.fIfTrue);
1279 if (stmt.fIfFalse) {
1280 this->write(" else ");
1281 this->writeStatement(*stmt.fIfFalse);
1282 }
1283}
1284
1285void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1286 this->write("for (");
1287 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1288 this->writeStatement(*f.fInitializer);
1289 } else {
1290 this->write("; ");
1291 }
1292 if (f.fTest) {
1293 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1294 }
1295 this->write("; ");
1296 if (f.fNext) {
1297 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1298 }
1299 this->write(") ");
1300 this->writeStatement(*f.fStatement);
1301}
1302
1303void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1304 this->write("while (");
1305 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1306 this->write(") ");
1307 this->writeStatement(*w.fStatement);
1308}
1309
1310void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1311 this->write("do ");
1312 this->writeStatement(*d.fStatement);
1313 this->write(" while (");
1314 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1315 this->write(");");
1316}
1317
1318void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1319 this->write("switch (");
1320 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1321 this->writeLine(") {");
1322 fIndentation++;
1323 for (const auto& c : s.fCases) {
1324 if (c->fValue) {
1325 this->write("case ");
1326 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1327 this->writeLine(":");
1328 } else {
1329 this->writeLine("default:");
1330 }
1331 fIndentation++;
1332 for (const auto& stmt : c->fStatements) {
1333 this->writeStatement(*stmt);
1334 this->writeLine();
1335 }
1336 fIndentation--;
1337 }
1338 fIndentation--;
1339 this->write("}");
1340}
1341
1342void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1343 this->write("return");
1344 if (r.fExpression) {
1345 this->write(" ");
1346 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1347 }
1348 this->write(";");
1349}
1350
1351void MetalCodeGenerator::writeHeader() {
1352 this->write("#include <metal_stdlib>\n");
1353 this->write("#include <simd/simd.h>\n");
1354 this->write("using namespace metal;\n");
1355}
1356
1357void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001358 for (const auto& e : fProgram) {
1359 if (ProgramElement::kVar_Kind == e.fKind) {
1360 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001361 if (!decls.fVars.size()) {
1362 continue;
1363 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001364 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001365 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1366 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001367 if (-1 == fUniformBuffer) {
1368 this->write("struct Uniforms {\n");
1369 fUniformBuffer = first.fModifiers.fLayout.fSet;
1370 if (-1 == fUniformBuffer) {
1371 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1372 }
1373 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1374 if (-1 == fUniformBuffer) {
1375 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1376 "the same 'layout(set=...)'");
1377 }
1378 }
1379 this->write(" ");
1380 this->writeType(first.fType);
1381 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001382 for (const auto& stmt : decls.fVars) {
1383 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001384 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001385 }
1386 this->write(";\n");
1387 }
1388 }
1389 }
1390 if (-1 != fUniformBuffer) {
1391 this->write("};\n");
1392 }
1393}
1394
1395void MetalCodeGenerator::writeInputStruct() {
1396 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001397 for (const auto& e : fProgram) {
1398 if (ProgramElement::kVar_Kind == e.fKind) {
1399 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001400 if (!decls.fVars.size()) {
1401 continue;
1402 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001403 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001404 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1405 -1 == first.fModifiers.fLayout.fBuiltin) {
1406 this->write(" ");
1407 this->writeType(first.fType);
1408 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001409 for (const auto& stmt : decls.fVars) {
1410 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001411 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001412 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001413 if (fProgram.fKind == Program::kVertex_Kind) {
1414 this->write(" [[attribute(" +
1415 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1416 } else if (fProgram.fKind == Program::kFragment_Kind) {
1417 this->write(" [[user(locn" +
1418 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1419 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001420 }
1421 }
1422 this->write(";\n");
1423 }
1424 }
1425 }
1426 this->write("};\n");
1427}
1428
1429void MetalCodeGenerator::writeOutputStruct() {
1430 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001431 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001432 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001433 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001434 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001435 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001436 for (const auto& e : fProgram) {
1437 if (ProgramElement::kVar_Kind == e.fKind) {
1438 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 if (!decls.fVars.size()) {
1440 continue;
1441 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001442 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001443 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1444 -1 == first.fModifiers.fLayout.fBuiltin) {
1445 this->write(" ");
1446 this->writeType(first.fType);
1447 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001448 for (const auto& stmt : decls.fVars) {
1449 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001450 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001451 if (fProgram.fKind == Program::kVertex_Kind) {
1452 this->write(" [[user(locn" +
1453 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1454 } else if (fProgram.fKind == Program::kFragment_Kind) {
1455 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001456 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1457 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1458 if (colorIndex) {
1459 this->write(", index(" + to_string(colorIndex) + ")");
1460 }
1461 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001462 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001463 }
1464 this->write(";\n");
1465 }
1466 }
Timothy Liang7d637782018-06-05 09:58:07 -04001467 }
1468 if (fProgram.fKind == Program::kVertex_Kind) {
1469 this->write(" float sk_PointSize;\n");
1470 }
1471 this->write("};\n");
1472}
1473
1474void MetalCodeGenerator::writeInterfaceBlocks() {
1475 bool wroteInterfaceBlock = false;
1476 for (const auto& e : fProgram) {
1477 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1478 this->writeInterfaceBlock((InterfaceBlock&) e);
1479 wroteInterfaceBlock = true;
1480 }
1481 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001482 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001483 this->writeLine("struct sksl_synthetic_uniforms {");
1484 this->writeLine(" float u_skRTHeight;");
1485 this->writeLine("};");
1486 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001487}
1488
Timothy Liangee84fe12018-05-18 14:38:19 -04001489void MetalCodeGenerator::writeGlobalStruct() {
1490 bool wroteStructDecl = false;
John Stilesc67b3622020-05-28 17:53:13 -04001491 auto WriteStructDecl = [&] {
Timothy Liang7d637782018-06-05 09:58:07 -04001492 if (!wroteStructDecl) {
1493 this->write("struct Globals {\n");
1494 wroteStructDecl = true;
1495 }
John Stilesc67b3622020-05-28 17:53:13 -04001496 };
1497
1498 for (const auto& intf : fInterfaceBlockNameMap) {
1499 WriteStructDecl();
Timothy Liang7d637782018-06-05 09:58:07 -04001500 fNeedsGlobalStructInit = true;
1501 const auto& intfType = intf.first;
1502 const auto& intfName = intf.second;
1503 this->write(" constant ");
1504 this->write(intfType->fTypeName);
1505 this->write("* ");
Timothy Liang651286f2018-06-07 09:55:33 -04001506 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -04001507 this->write(";\n");
1508 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001509 for (const auto& e : fProgram) {
1510 if (ProgramElement::kVar_Kind == e.fKind) {
1511 VarDeclarations& decls = (VarDeclarations&) e;
1512 if (!decls.fVars.size()) {
1513 continue;
1514 }
1515 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001516 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1517 first.fType.kind() == Type::kSampler_Kind) {
John Stilesc67b3622020-05-28 17:53:13 -04001518 WriteStructDecl();
Timothy Liangee84fe12018-05-18 14:38:19 -04001519 fNeedsGlobalStructInit = true;
1520 this->write(" ");
1521 this->writeType(first.fType);
1522 this->write(" ");
1523 for (const auto& stmt : decls.fVars) {
1524 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001525 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001526 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1527 fTextures.push_back(var.fVar);
1528 this->write(";\n");
1529 this->write(" sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -04001530 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001531 this->write(SAMPLER_SUFFIX);
1532 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001533 if (var.fValue) {
1534 fInitNonConstGlobalVars.push_back(&var);
1535 }
1536 }
1537 this->write(";\n");
1538 }
1539 }
1540 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001541 if (wroteStructDecl) {
1542 this->write("};\n");
1543 }
1544}
1545
Ethan Nicholascc305772017-10-13 16:17:45 -04001546void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1547 switch (e.fKind) {
1548 case ProgramElement::kExtension_Kind:
1549 break;
1550 case ProgramElement::kVar_Kind: {
1551 VarDeclarations& decl = (VarDeclarations&) e;
1552 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001553 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001554 if (-1 == builtin) {
1555 // normal var
1556 this->writeVarDeclarations(decl, true);
1557 this->writeLine();
1558 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1559 // ignore
1560 }
1561 }
1562 break;
1563 }
1564 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001565 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001566 break;
1567 case ProgramElement::kFunction_Kind:
1568 this->writeFunction((FunctionDefinition&) e);
1569 break;
1570 case ProgramElement::kModifiers_Kind:
1571 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1572 this->writeLine(";");
1573 break;
1574 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001575#ifdef SK_DEBUG
1576 ABORT("unsupported program element: %s\n", e.description().c_str());
1577#endif
1578 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001579 }
1580}
1581
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001582MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1583 if (!e) {
1584 return kNo_Requirements;
1585 }
1586 switch (e->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001587 case Expression::kFunctionCall_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001588 const FunctionCall& f = (const FunctionCall&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001589 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001590 for (const auto& arg : f.fArguments) {
1591 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001592 }
1593 return result;
1594 }
1595 case Expression::kConstructor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001596 const Constructor& c = (const Constructor&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001597 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001598 for (const auto& arg : c.fArguments) {
1599 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001600 }
1601 return result;
1602 }
Timothy Liang7d637782018-06-05 09:58:07 -04001603 case Expression::kFieldAccess_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001604 const FieldAccess& f = (const FieldAccess&) *e;
Timothy Liang7d637782018-06-05 09:58:07 -04001605 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1606 return kGlobals_Requirement;
1607 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001608 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001609 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001610 case Expression::kSwizzle_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001611 return this->requirements(((const Swizzle&) *e).fBase.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001612 case Expression::kBinary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001613 const BinaryExpression& b = (const BinaryExpression&) *e;
1614 return this->requirements(b.fLeft.get()) | this->requirements(b.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001615 }
1616 case Expression::kIndex_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001617 const IndexExpression& idx = (const IndexExpression&) *e;
1618 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001619 }
1620 case Expression::kPrefix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001621 return this->requirements(((const PrefixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001622 case Expression::kPostfix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001623 return this->requirements(((const PostfixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001624 case Expression::kTernary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001625 const TernaryExpression& t = (const TernaryExpression&) *e;
1626 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1627 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001628 }
1629 case Expression::kVariableReference_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001630 const VariableReference& v = (const VariableReference&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001631 Requirements result = kNo_Requirements;
1632 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001633 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001634 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1635 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1636 result = kInputs_Requirement;
1637 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1638 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001639 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1640 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001641 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001642 } else {
1643 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001644 }
1645 }
1646 return result;
1647 }
1648 default:
1649 return kNo_Requirements;
1650 }
1651}
1652
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001653MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1654 if (!s) {
1655 return kNo_Requirements;
1656 }
1657 switch (s->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001658 case Statement::kBlock_Kind: {
1659 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001660 for (const auto& child : ((const Block*) s)->fStatements) {
1661 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001662 }
1663 return result;
1664 }
Timothy Liang7d637782018-06-05 09:58:07 -04001665 case Statement::kVarDeclaration_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001666 const VarDeclaration& var = (const VarDeclaration&) *s;
1667 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001668 }
1669 case Statement::kVarDeclarations_Kind: {
1670 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001671 const VarDeclarations& decls = *((const VarDeclarationsStatement&) *s).fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001672 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001673 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001674 }
1675 return result;
1676 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001677 case Statement::kExpression_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001678 return this->requirements(((const ExpressionStatement&) *s).fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001679 case Statement::kReturn_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001680 const ReturnStatement& r = (const ReturnStatement&) *s;
1681 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001682 }
1683 case Statement::kIf_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001684 const IfStatement& i = (const IfStatement&) *s;
1685 return this->requirements(i.fTest.get()) |
1686 this->requirements(i.fIfTrue.get()) |
1687 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001688 }
1689 case Statement::kFor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001690 const ForStatement& f = (const ForStatement&) *s;
1691 return this->requirements(f.fInitializer.get()) |
1692 this->requirements(f.fTest.get()) |
1693 this->requirements(f.fNext.get()) |
1694 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001695 }
1696 case Statement::kWhile_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001697 const WhileStatement& w = (const WhileStatement&) *s;
1698 return this->requirements(w.fTest.get()) |
1699 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001700 }
1701 case Statement::kDo_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001702 const DoStatement& d = (const DoStatement&) *s;
1703 return this->requirements(d.fTest.get()) |
1704 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001705 }
1706 case Statement::kSwitch_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001707 const SwitchStatement& sw = (const SwitchStatement&) *s;
1708 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001709 for (const auto& c : sw.fCases) {
1710 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001711 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001712 }
1713 }
1714 return result;
1715 }
1716 default:
1717 return kNo_Requirements;
1718 }
1719}
1720
1721MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1722 if (f.fBuiltin) {
1723 return kNo_Requirements;
1724 }
1725 auto found = fRequirements.find(&f);
1726 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001727 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001728 for (const auto& e : fProgram) {
1729 if (ProgramElement::kFunction_Kind == e.fKind) {
1730 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001731 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001732 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001733 fRequirements[&f] = reqs;
1734 return reqs;
1735 }
1736 }
1737 }
1738 }
1739 return found->second;
1740}
1741
Timothy Liangb8eeb802018-07-23 16:46:16 -04001742bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001743 OutputStream* rawOut = fOut;
1744 fOut = &fHeader;
1745 fProgramKind = fProgram.fKind;
1746 this->writeHeader();
1747 this->writeUniformStruct();
1748 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001749 this->writeOutputStruct();
1750 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001751 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001752 StringStream body;
1753 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001754 for (const auto& e : fProgram) {
1755 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001756 }
1757 fOut = rawOut;
1758
1759 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001760 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 write_stringstream(body, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001762 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001763}
1764
1765}