blob: 7aadc1a26c0c84b3b696cf8072348e3ae64ed306 [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
John Stilescdcdb042020-07-06 09:03:51 -040020class MetalCodeGenerator::GlobalStructVisitor {
21public:
22 virtual ~GlobalStructVisitor() = default;
23 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
24 virtual void VisitTexture(const Type& type, const String& name) = 0;
25 virtual void VisitSampler(const Type& type, const String& name) = 0;
26 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
27};
28
Timothy Liangee84fe12018-05-18 14:38:19 -040029void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040030#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
31#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040032 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040033 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050034 fIntrinsicMap[String("equal")] = METAL(Equal);
35 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040036 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
37 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
38 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
39 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040040}
41
Ethan Nicholascc305772017-10-13 16:17:45 -040042void MetalCodeGenerator::write(const char* s) {
43 if (!s[0]) {
44 return;
45 }
46 if (fAtLineStart) {
47 for (int i = 0; i < fIndentation; i++) {
48 fOut->writeText(" ");
49 }
50 }
51 fOut->writeText(s);
52 fAtLineStart = false;
53}
54
55void MetalCodeGenerator::writeLine(const char* s) {
56 this->write(s);
57 fOut->writeText(fLineEnding);
58 fAtLineStart = true;
59}
60
61void MetalCodeGenerator::write(const String& s) {
62 this->write(s.c_str());
63}
64
65void MetalCodeGenerator::writeLine(const String& s) {
66 this->writeLine(s.c_str());
67}
68
69void MetalCodeGenerator::writeLine() {
70 this->writeLine("");
71}
72
73void MetalCodeGenerator::writeExtension(const Extension& ext) {
74 this->writeLine("#extension " + ext.fName + " : enable");
75}
76
Ethan Nicholas45fa8102020-01-13 10:58:49 -050077String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholascc305772017-10-13 16:17:45 -040078 switch (type.kind()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040079 case Type::kVector_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050080 return this->typeName(type.componentType()) + to_string(type.columns());
Timothy Liang43d225f2018-07-19 15:27:13 -040081 case Type::kMatrix_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050082 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
83 to_string(type.rows());
Timothy Liangee84fe12018-05-18 14:38:19 -040084 case Type::kSampler_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050085 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040086 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040087 if (type == *fContext.fHalf_Type) {
88 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050089 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040090 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050091 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040092 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050093 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040094 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050095 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040096 }
Ethan Nicholascc305772017-10-13 16:17:45 -040097 }
98}
99
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500100void MetalCodeGenerator::writeType(const Type& type) {
101 if (type.kind() == Type::kStruct_Kind) {
102 for (const Type* search : fWrittenStructs) {
103 if (*search == type) {
104 // already written
105 this->write(type.name());
106 return;
107 }
108 }
109 fWrittenStructs.push_back(&type);
110 this->writeLine("struct " + type.name() + " {");
111 fIndentation++;
112 this->writeFields(type.fields(), type.fOffset);
113 fIndentation--;
114 this->write("}");
115 } else {
116 this->write(this->typeName(type));
117 }
118}
119
Ethan Nicholascc305772017-10-13 16:17:45 -0400120void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
121 switch (expr.fKind) {
122 case Expression::kBinary_Kind:
123 this->writeBinaryExpression((BinaryExpression&) expr, parentPrecedence);
124 break;
125 case Expression::kBoolLiteral_Kind:
126 this->writeBoolLiteral((BoolLiteral&) expr);
127 break;
128 case Expression::kConstructor_Kind:
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500129 this->writeConstructor((Constructor&) expr, parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400130 break;
131 case Expression::kIntLiteral_Kind:
132 this->writeIntLiteral((IntLiteral&) expr);
133 break;
134 case Expression::kFieldAccess_Kind:
135 this->writeFieldAccess(((FieldAccess&) expr));
136 break;
137 case Expression::kFloatLiteral_Kind:
138 this->writeFloatLiteral(((FloatLiteral&) expr));
139 break;
140 case Expression::kFunctionCall_Kind:
141 this->writeFunctionCall((FunctionCall&) expr);
142 break;
143 case Expression::kPrefix_Kind:
144 this->writePrefixExpression((PrefixExpression&) expr, parentPrecedence);
145 break;
146 case Expression::kPostfix_Kind:
147 this->writePostfixExpression((PostfixExpression&) expr, parentPrecedence);
148 break;
149 case Expression::kSetting_Kind:
150 this->writeSetting((Setting&) expr);
151 break;
152 case Expression::kSwizzle_Kind:
153 this->writeSwizzle((Swizzle&) expr);
154 break;
155 case Expression::kVariableReference_Kind:
156 this->writeVariableReference((VariableReference&) expr);
157 break;
158 case Expression::kTernary_Kind:
159 this->writeTernaryExpression((TernaryExpression&) expr, parentPrecedence);
160 break;
161 case Expression::kIndex_Kind:
162 this->writeIndexExpression((IndexExpression&) expr);
163 break;
164 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500165#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500167#endif
168 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 }
170}
171
Timothy Liang6403b0e2018-05-17 10:40:04 -0400172void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400173 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400174 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400175 Intrinsic intrinsic = i->second;
176 int32_t intrinsicId = intrinsic.second;
177 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400178 case kSpecial_IntrinsicKind:
179 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400180 break;
181 case kMetal_IntrinsicKind:
182 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
183 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500184 case kEqual_MetalIntrinsic:
185 this->write(" == ");
186 break;
187 case kNotEqual_MetalIntrinsic:
188 this->write(" != ");
189 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400190 case kLessThan_MetalIntrinsic:
191 this->write(" < ");
192 break;
193 case kLessThanEqual_MetalIntrinsic:
194 this->write(" <= ");
195 break;
196 case kGreaterThan_MetalIntrinsic:
197 this->write(" > ");
198 break;
199 case kGreaterThanEqual_MetalIntrinsic:
200 this->write(" >= ");
201 break;
202 default:
203 ABORT("unsupported metal intrinsic kind");
204 }
205 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
206 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400207 default:
208 ABORT("unsupported intrinsic kind");
209 }
210}
211
Ethan Nicholascc305772017-10-13 16:17:45 -0400212void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400213 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
214 if (entry != fIntrinsicMap.end()) {
215 this->writeIntrinsicCall(c);
216 return;
217 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400218 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
219 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400220 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
221 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500222 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
223 SkASSERT(c.fArguments.size() == 1);
224 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400225 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
226 this->write("dfdx");
227 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700228 // Flipping Y also negates the Y derivatives.
229 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400230 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400231 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400232 }
233 this->write("(");
234 const char* separator = "";
235 if (this->requirements(c.fFunction) & kInputs_Requirement) {
236 this->write("_in");
237 separator = ", ";
238 }
239 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
240 this->write(separator);
241 this->write("_out");
242 separator = ", ";
243 }
244 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
245 this->write(separator);
246 this->write("_uniforms");
247 separator = ", ";
248 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400249 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
250 this->write(separator);
251 this->write("_globals");
252 separator = ", ";
253 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400254 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
255 this->write(separator);
256 this->write("_fragCoord");
257 separator = ", ";
258 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400259 for (size_t i = 0; i < c.fArguments.size(); ++i) {
260 const Expression& arg = *c.fArguments[i];
261 this->write(separator);
262 separator = ", ";
263 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
264 this->write("&");
265 }
266 this->writeExpression(arg, kSequence_Precedence);
267 }
268 this->write(")");
269}
270
Chris Daltondba7aab2018-11-15 10:57:49 -0500271void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500272 String typeName = mat.fType.name();
273 String name = typeName + "_inverse";
274 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500275 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
276 fWrittenIntrinsics.insert(name);
277 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500278 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500279 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
280 "}"
281 ).c_str());
282 }
283 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500284 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
285 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
286 fWrittenIntrinsics.insert(name);
287 fExtraFunctions.writeText((
288 typeName + " " + name + "(" + typeName + " m) {"
289 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
290 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
291 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
292 " float b01 = a22 * a11 - a12 * a21;"
293 " float b11 = -a22 * a10 + a12 * a20;"
294 " float b21 = a21 * a10 - a11 * a20;"
295 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
296 " return " + typeName +
297 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
298 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
299 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
300 " (1/det);"
301 "}"
302 ).c_str());
303 }
304 }
305 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
306 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
307 fWrittenIntrinsics.insert(name);
308 fExtraFunctions.writeText((
309 typeName + " " + name + "(" + typeName + " m) {"
310 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
311 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
312 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
313 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
314 " float b00 = a00 * a11 - a01 * a10;"
315 " float b01 = a00 * a12 - a02 * a10;"
316 " float b02 = a00 * a13 - a03 * a10;"
317 " float b03 = a01 * a12 - a02 * a11;"
318 " float b04 = a01 * a13 - a03 * a11;"
319 " float b05 = a02 * a13 - a03 * a12;"
320 " float b06 = a20 * a31 - a21 * a30;"
321 " float b07 = a20 * a32 - a22 * a30;"
322 " float b08 = a20 * a33 - a23 * a30;"
323 " float b09 = a21 * a32 - a22 * a31;"
324 " float b10 = a21 * a33 - a23 * a31;"
325 " float b11 = a22 * a33 - a23 * a32;"
326 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
327 " b04 * b07 + b05 * b06;"
328 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
329 " a02 * b10 - a01 * b11 - a03 * b09,"
330 " a31 * b05 - a32 * b04 + a33 * b03,"
331 " a22 * b04 - a21 * b05 - a23 * b03,"
332 " a12 * b08 - a10 * b11 - a13 * b07,"
333 " a00 * b11 - a02 * b08 + a03 * b07,"
334 " a32 * b02 - a30 * b05 - a33 * b01,"
335 " a20 * b05 - a22 * b02 + a23 * b01,"
336 " a10 * b10 - a11 * b08 + a13 * b06,"
337 " a01 * b08 - a00 * b10 - a03 * b06,"
338 " a30 * b04 - a31 * b02 + a33 * b00,"
339 " a21 * b02 - a20 * b04 - a23 * b00,"
340 " a11 * b07 - a10 * b09 - a12 * b06,"
341 " a00 * b09 - a01 * b07 + a02 * b06,"
342 " a31 * b01 - a30 * b03 - a32 * b00,"
343 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
344 "}"
345 ).c_str());
346 }
347 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500348 this->write(name);
349}
350
Timothy Liang6403b0e2018-05-17 10:40:04 -0400351void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
352 switch (kind) {
353 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400354 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400355 this->write(".sample(");
356 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
357 this->write(SAMPLER_SUFFIX);
358 this->write(", ");
Timothy Liangee84fe12018-05-18 14:38:19 -0400359 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500360 // have to store the vector in a temp variable to avoid double evaluating it
361 String tmpVar = "tmpCoord" + to_string(fVarCount++);
362 this->fFunctionHeader += " " + this->typeName(c.fArguments[1]->fType) + " " +
363 tmpVar + ";\n";
364 this->write("(" + tmpVar + " = ");
365 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
366 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400367 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400368 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500369 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400370 this->write(")");
371 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400372 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500373 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400374 // 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 -0500375 String tmpX = "tmpX" + to_string(fVarCount++);
376 String tmpY = "tmpY" + to_string(fVarCount++);
377 this->fFunctionHeader += " " + this->typeName(c.fArguments[0]->fType) + " " + tmpX +
378 ", " + tmpY + ";\n";
379 this->write("(" + tmpX + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400380 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500381 this->write(", " + tmpY + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400382 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500383 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400384 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500385 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400386 default:
387 ABORT("unsupported special intrinsic kind");
388 }
389}
390
John Stilesfcf8cb22020-08-06 14:29:22 -0400391// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
392// Cells that don't exist in the source matrix will be populated with identity-matrix values.
393void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
394 SkASSERT(rows <= 4);
395 SkASSERT(columns <= 4);
396
397 const char* columnSeparator = "";
398 for (int c = 0; c < columns; ++c) {
399 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
400 columnSeparator = "), ";
401
402 // Determine how many values to take from the source matrix for this row.
403 int swizzleLength = 0;
404 if (c < sourceMatrix.columns()) {
405 swizzleLength = std::min<>(rows, sourceMatrix.rows());
406 }
407
408 // Emit all the values from the source matrix row.
409 bool firstItem;
410 switch (swizzleLength) {
411 case 0: firstItem = true; break;
412 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
413 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
414 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
415 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
416 default: SkUNREACHABLE;
417 }
418
419 // Emit the placeholder identity-matrix cells.
420 for (int r = swizzleLength; r < rows; ++r) {
421 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
422 firstItem = false;
423 }
424 }
425
426 fExtraFunctions.writeText(")");
427}
428
429// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
430// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
431void MetalCodeGenerator::assembleMatrixFromExpressions(
432 const std::vector<std::unique_ptr<Expression>>& args, int rows, int columns) {
433 size_t argIndex = 0;
434 int argPosition = 0;
435
436 const char* columnSeparator = "";
437 for (int c = 0; c < columns; ++c) {
438 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
439 columnSeparator = "), ";
440
441 const char* rowSeparator = "";
442 for (int r = 0; r < rows; ++r) {
443 fExtraFunctions.writeText(rowSeparator);
444 rowSeparator = ", ";
445
446 if (argIndex < args.size()) {
447 const Type& argType = args[argIndex]->fType;
448 switch (argType.kind()) {
449 case Type::kScalar_Kind: {
450 fExtraFunctions.printf("x%zu", argIndex);
451 break;
452 }
453 case Type::kVector_Kind: {
454 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
455 break;
456 }
457 case Type::kMatrix_Kind: {
458 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
459 argPosition / argType.rows(),
460 argPosition % argType.rows());
461 break;
462 }
463 default: {
464 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
465 fExtraFunctions.writeText("<error>");
466 break;
467 }
468 }
469
470 ++argPosition;
471 if (argPosition >= argType.columns() * argType.rows()) {
472 ++argIndex;
473 argPosition = 0;
474 }
475 } else {
476 SkDEBUGFAIL("not enough arguments for matrix constructor");
477 fExtraFunctions.writeText("<error>");
478 }
479 }
480 }
481
482 if (argPosition != 0 || argIndex != args.size()) {
483 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
484 fExtraFunctions.writeText(", <error>");
485 }
486
487 fExtraFunctions.writeText(")");
488}
489
John Stiles1bdafbf2020-05-28 12:17:20 -0400490// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
491// Keeps track of previously generated constructors so that we won't generate more than one
492// constructor for any given permutation of input argument types. Returns the name of the
493// generated constructor method.
494String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
495 const Type& matrix = c.fType;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500496 int columns = matrix.columns();
497 int rows = matrix.rows();
John Stiles1bdafbf2020-05-28 12:17:20 -0400498 const std::vector<std::unique_ptr<Expression>>& args = c.fArguments;
499
500 // Create the helper-method name and use it as our lookup key.
501 String name;
502 name.appendf("float%dx%d_from", columns, rows);
503 for (const std::unique_ptr<Expression>& expr : args) {
504 name.appendf("_%s", expr->fType.displayName().c_str());
505 }
506
507 // If a helper-method has already been synthesized, we don't need to synthesize it again.
508 auto [iter, newlyCreated] = fHelpers.insert(name);
509 if (!newlyCreated) {
510 return name;
511 }
512
513 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
514 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
515 // supply a mixture of scalars and vectors.)
516 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
517
518 size_t argIndex = 0;
519 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400520 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400521 fExtraFunctions.printf("%s%s x%zu", argSeparator,
522 expr->fType.displayName().c_str(), argIndex++);
523 argSeparator = ", ";
524 }
525
526 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
527
John Stilesfcf8cb22020-08-06 14:29:22 -0400528 if (args.size() == 1 && args.front()->fType.kind() == Type::kMatrix_Kind) {
529 this->assembleMatrixFromMatrix(args.front()->fType, rows, columns);
530 } else {
531 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400532 }
533
John Stilesfcf8cb22020-08-06 14:29:22 -0400534 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500535 return name;
536}
537
538bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
539 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
540 return false;
541 }
542 if (t1.columns() > 1) {
543 return this->canCoerce(t1.componentType(), t2.componentType());
544 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500545 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500546}
547
John Stiles1bdafbf2020-05-28 12:17:20 -0400548bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
549 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
550 if (c.fType.kind() != Type::kMatrix_Kind) {
551 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500552 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400553
554 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
555 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
556 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
557 // scalars can be constructed trivially. In more complex cases, we generate a helper function
558 // that converts our inputs into a properly-shaped matrix.
559 // A matrix construct helper method is always used if any input argument is a matrix.
560 // Helper methods are also necessary when any argument would span multiple rows. For instance:
561 //
562 // float2 x = (1, 2);
563 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
564 // | 2 4 6 |
565 //
566 // float2 x = (2, 3);
567 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
568 // | 2 4 6 |
569 //
570 // float4 x = (1, 2, 3, 4);
571 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
572 // | 2 4 |
573 //
574
575 int position = 0;
576 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
577 // If an input argument is a matrix, we need a helper function.
578 if (expr->fType.kind() == Type::kMatrix_Kind) {
579 return true;
580 }
581 position += expr->fType.columns();
582 if (position > c.fType.rows()) {
583 // An input argument would span multiple rows; a helper function is required.
584 return true;
585 }
586 if (position == c.fType.rows()) {
587 // We've advanced to the end of a row. Wrap to the start of the next row.
588 position = 0;
589 }
590 }
591
592 return false;
593}
594
595void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
596 // Handle special cases for single-argument constructors.
597 if (c.fArguments.size() == 1) {
598 // If the type is coercible, emit it directly.
599 const Expression& arg = *c.fArguments.front();
600 if (this->canCoerce(c.fType, arg.fType)) {
601 this->writeExpression(arg, parentPrecedence);
602 return;
603 }
604
605 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
606 // matrix constructor.
607 if (c.fType.kind() == Type::kMatrix_Kind && arg.fType.isNumber()) {
608 const Type& matrix = c.fType;
609 this->write("float");
610 this->write(to_string(matrix.columns()));
611 this->write("x");
612 this->write(to_string(matrix.rows()));
613 this->write("(");
614 this->writeExpression(arg, parentPrecedence);
615 this->write(")");
616 return;
617 }
618 }
619
620 // Emit and invoke a matrix-constructor helper method if one is necessary.
621 if (this->matrixConstructHelperIsNeeded(c)) {
622 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000623 this->write("(");
624 const char* separator = "";
John Stiles1bdafbf2020-05-28 12:17:20 -0400625 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
John Stiles1fa15b12020-05-28 17:36:54 +0000626 this->write(separator);
627 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400628 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400629 }
John Stiles1fa15b12020-05-28 17:36:54 +0000630 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400631 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400632 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400633
634 // Explicitly invoke the constructor, passing in the necessary arguments.
635 this->writeType(c.fType);
636 this->write("(");
637 const char* separator = "";
638 int scalarCount = 0;
639 for (const std::unique_ptr<Expression>& arg : c.fArguments) {
640 this->write(separator);
641 separator = ", ";
642 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() < c.fType.rows()) {
643 // Merge scalars and smaller vectors together.
644 if (!scalarCount) {
645 this->writeType(c.fType.componentType());
646 this->write(to_string(c.fType.rows()));
647 this->write("(");
648 }
649 scalarCount += arg->fType.columns();
650 }
651 this->writeExpression(*arg, kSequence_Precedence);
652 if (scalarCount && scalarCount == c.fType.rows()) {
653 this->write(")");
654 scalarCount = 0;
655 }
656 }
657 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400658}
659
660void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400661 if (fRTHeightName.length()) {
662 this->write("float4(_fragCoord.x, ");
663 this->write(fRTHeightName.c_str());
664 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500665 } else {
666 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
667 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400668}
669
670void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
671 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
672 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400673 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400674 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400675 case SK_FRAGCOORD_BUILTIN:
676 this->writeFragCoord();
677 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400678 case SK_VERTEXID_BUILTIN:
679 this->write("sk_VertexID");
680 break;
681 case SK_INSTANCEID_BUILTIN:
682 this->write("sk_InstanceID");
683 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400684 case SK_CLOCKWISE_BUILTIN:
685 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400686 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400687 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
688 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400689 default:
690 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
691 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
692 this->write("_in.");
693 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400694 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400695 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
696 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400697 this->write("_uniforms.");
698 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400699 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400700 }
701 }
Timothy Liang651286f2018-06-07 09:55:33 -0400702 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400703 }
704}
705
706void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
707 this->writeExpression(*expr.fBase, kPostfix_Precedence);
708 this->write("[");
709 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
710 this->write("]");
711}
712
713void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400714 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400715 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
716 this->writeExpression(*f.fBase, kPostfix_Precedence);
717 this->write(".");
718 }
Timothy Liang7d637782018-06-05 09:58:07 -0400719 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400720 case SK_CLIPDISTANCE_BUILTIN:
721 this->write("gl_ClipDistance");
722 break;
723 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400724 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400725 break;
726 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400727 if (field->fName == "sk_PointSize") {
728 this->write("_out->sk_PointSize");
729 } else {
730 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
731 this->write("_globals->");
732 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
733 this->write("->");
734 }
Timothy Liang651286f2018-06-07 09:55:33 -0400735 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400736 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400737 }
738}
739
740void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500741 int last = swizzle.fComponents.back();
742 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
743 this->writeType(swizzle.fType);
744 this->write("(");
745 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400746 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
747 this->write(".");
748 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500749 if (c >= 0) {
750 this->write(&("x\0y\0z\0w\0"[c * 2]));
751 }
752 }
753 if (last == SKSL_SWIZZLE_0) {
754 this->write(", 0)");
755 }
756 else if (last == SKSL_SWIZZLE_1) {
757 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400758 }
759}
760
761MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
762 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400763 case Token::Kind::TK_STAR: // fall through
764 case Token::Kind::TK_SLASH: // fall through
765 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
766 case Token::Kind::TK_PLUS: // fall through
767 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
768 case Token::Kind::TK_SHL: // fall through
769 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
770 case Token::Kind::TK_LT: // fall through
771 case Token::Kind::TK_GT: // fall through
772 case Token::Kind::TK_LTEQ: // fall through
773 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
774 case Token::Kind::TK_EQEQ: // fall through
775 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
776 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
777 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
778 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
779 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
780 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
781 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
782 case Token::Kind::TK_EQ: // fall through
783 case Token::Kind::TK_PLUSEQ: // fall through
784 case Token::Kind::TK_MINUSEQ: // fall through
785 case Token::Kind::TK_STAREQ: // fall through
786 case Token::Kind::TK_SLASHEQ: // fall through
787 case Token::Kind::TK_PERCENTEQ: // fall through
788 case Token::Kind::TK_SHLEQ: // fall through
789 case Token::Kind::TK_SHREQ: // fall through
790 case Token::Kind::TK_LOGICALANDEQ: // fall through
791 case Token::Kind::TK_LOGICALXOREQ: // fall through
792 case Token::Kind::TK_LOGICALOREQ: // fall through
793 case Token::Kind::TK_BITWISEANDEQ: // fall through
794 case Token::Kind::TK_BITWISEXOREQ: // fall through
795 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
796 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400797 default: ABORT("unsupported binary operator");
798 }
799}
800
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500801void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
802 const Type& result) {
803 String key = "TimesEqual" + left.name() + right.name();
804 if (fHelpers.find(key) == fHelpers.end()) {
805 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
806 " left = left * right;\n"
807 " return left;\n"
808 "}", result.name().c_str(), left.name().c_str(),
809 right.name().c_str());
810 }
811}
812
Ethan Nicholascc305772017-10-13 16:17:45 -0400813void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
814 Precedence parentPrecedence) {
815 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500816 bool needParens = precedence >= parentPrecedence;
817 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400818 case Token::Kind::TK_EQEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500819 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
820 this->write("all");
821 needParens = true;
822 }
823 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400824 case Token::Kind::TK_NEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500825 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400826 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500827 needParens = true;
828 }
829 break;
830 default:
831 break;
832 }
833 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400834 this->write("(");
835 }
836 if (Compiler::IsAssignment(b.fOperator) &&
837 Expression::kVariableReference_Kind == b.fLeft->fKind &&
838 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
839 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
840 // writing to an out parameter. Since we have to turn those into pointers, we have to
841 // dereference it here.
842 this->write("*");
843 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400844 if (b.fOperator == Token::Kind::TK_STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500845 b.fRight->fType.kind() == Type::kMatrix_Kind) {
846 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
847 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400848 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400849 if (b.fOperator != Token::Kind::TK_EQ && Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholascc305772017-10-13 16:17:45 -0400850 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
851 // This doesn't compile in Metal:
852 // float4 x = float4(1);
853 // x.xy *= float2x2(...);
854 // with the error message "non-const reference cannot bind to vector element",
855 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
856 // as long as the LHS has no side effects, and hope for the best otherwise.
857 this->write(" = ");
858 this->writeExpression(*b.fLeft, kAssignment_Precedence);
859 this->write(" ");
860 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400861 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400862 this->write(op.substr(0, op.size() - 1).c_str());
863 this->write(" ");
864 } else {
865 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
866 }
867 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500868 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400869 this->write(")");
870 }
871}
872
873void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
874 Precedence parentPrecedence) {
875 if (kTernary_Precedence >= parentPrecedence) {
876 this->write("(");
877 }
878 this->writeExpression(*t.fTest, kTernary_Precedence);
879 this->write(" ? ");
880 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
881 this->write(" : ");
882 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
883 if (kTernary_Precedence >= parentPrecedence) {
884 this->write(")");
885 }
886}
887
888void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
889 Precedence parentPrecedence) {
890 if (kPrefix_Precedence >= parentPrecedence) {
891 this->write("(");
892 }
893 this->write(Compiler::OperatorName(p.fOperator));
894 this->writeExpression(*p.fOperand, kPrefix_Precedence);
895 if (kPrefix_Precedence >= parentPrecedence) {
896 this->write(")");
897 }
898}
899
900void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
901 Precedence parentPrecedence) {
902 if (kPostfix_Precedence >= parentPrecedence) {
903 this->write("(");
904 }
905 this->writeExpression(*p.fOperand, kPostfix_Precedence);
906 this->write(Compiler::OperatorName(p.fOperator));
907 if (kPostfix_Precedence >= parentPrecedence) {
908 this->write(")");
909 }
910}
911
912void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
913 this->write(b.fValue ? "true" : "false");
914}
915
916void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
917 if (i.fType == *fContext.fUInt_Type) {
918 this->write(to_string(i.fValue & 0xffffffff) + "u");
919 } else {
920 this->write(to_string((int32_t) i.fValue));
921 }
922}
923
924void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
925 this->write(to_string(f.fValue));
926}
927
928void MetalCodeGenerator::writeSetting(const Setting& s) {
929 ABORT("internal error; setting was not folded to a constant during compilation\n");
930}
931
932void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400933 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400934 const char* separator = "";
935 if ("main" == f.fDeclaration.fName) {
936 switch (fProgram.fKind) {
937 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400938 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400939 break;
940 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400941 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400942 break;
943 default:
John Stilesf7d70432020-05-28 15:46:38 -0400944 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -0400945 }
946 this->write("(Inputs _in [[stage_in]]");
947 if (-1 != fUniformBuffer) {
948 this->write(", constant Uniforms& _uniforms [[buffer(" +
949 to_string(fUniformBuffer) + ")]]");
950 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400951 for (const auto& e : fProgram) {
952 if (ProgramElement::kVar_Kind == e.fKind) {
953 VarDeclarations& decls = (VarDeclarations&) e;
954 if (!decls.fVars.size()) {
955 continue;
956 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400957 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400958 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400959 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
John Stiles08cb2c12020-07-06 10:18:49 -0400960 if (var.fVar->fModifiers.fLayout.fBinding < 0) {
961 fErrors.error(decls.fOffset,
962 "Metal samplers must have 'layout(binding=...)'");
963 }
Timothy Liang7d637782018-06-05 09:58:07 -0400964 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400965 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400966 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400967 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
968 this->write(")]]");
969 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400970 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400971 this->write(SAMPLER_SUFFIX);
972 this->write("[[sampler(");
973 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400974 this->write(")]]");
975 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400976 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400977 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
978 InterfaceBlock& intf = (InterfaceBlock&) e;
979 if ("sk_PerVertex" == intf.fTypeName) {
980 continue;
981 }
982 this->write(", constant ");
983 this->writeType(intf.fVariable.fType);
984 this->write("& " );
985 this->write(fInterfaceBlockNameMap[&intf]);
986 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400987 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400988 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400989 }
990 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500991 if (fProgram.fKind == Program::kFragment_Kind) {
992 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400993 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400994 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400995 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400996 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400997 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400998 } else if (fProgram.fKind == Program::kVertex_Kind) {
999 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001000 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001001 separator = ", ";
1002 } else {
1003 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -04001004 this->write(" ");
1005 this->writeName(f.fDeclaration.fName);
1006 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001007 Requirements requirements = this->requirements(f.fDeclaration);
1008 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001009 this->write("Inputs _in");
1010 separator = ", ";
1011 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001012 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001013 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001014 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001015 separator = ", ";
1016 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001017 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001018 this->write(separator);
1019 this->write("Uniforms _uniforms");
1020 separator = ", ";
1021 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001022 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001023 this->write(separator);
1024 this->write("thread Globals* _globals");
1025 separator = ", ";
1026 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001027 if (requirements & kFragCoord_Requirement) {
1028 this->write(separator);
1029 this->write("float4 _fragCoord");
1030 separator = ", ";
1031 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001032 }
1033 for (const auto& param : f.fDeclaration.fParameters) {
1034 this->write(separator);
1035 separator = ", ";
1036 this->writeModifiers(param->fModifiers, false);
1037 std::vector<int> sizes;
1038 const Type* type = &param->fType;
1039 while (Type::kArray_Kind == type->kind()) {
1040 sizes.push_back(type->columns());
1041 type = &type->componentType();
1042 }
1043 this->writeType(*type);
1044 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
1045 this->write("*");
1046 }
Timothy Liang651286f2018-06-07 09:55:33 -04001047 this->write(" ");
1048 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001049 for (int s : sizes) {
1050 if (s <= 0) {
1051 this->write("[]");
1052 } else {
1053 this->write("[" + to_string(s) + "]");
1054 }
1055 }
1056 }
1057 this->writeLine(") {");
1058
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001059 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001060
Ethan Nicholascc305772017-10-13 16:17:45 -04001061 if ("main" == f.fDeclaration.fName) {
John Stilescdcdb042020-07-06 09:03:51 -04001062 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001063 this->writeLine(" Outputs _outputStruct;");
1064 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001065 }
John Stilesc67b3622020-05-28 17:53:13 -04001066
Ethan Nicholascc305772017-10-13 16:17:45 -04001067 fFunctionHeader = "";
1068 OutputStream* oldOut = fOut;
1069 StringStream buffer;
1070 fOut = &buffer;
1071 fIndentation++;
1072 this->writeStatements(((Block&) *f.fBody).fStatements);
1073 if ("main" == f.fDeclaration.fName) {
1074 switch (fProgram.fKind) {
1075 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001076 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001077 break;
1078 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001079 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001080 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001081 break;
1082 default:
John Stilesf7d70432020-05-28 15:46:38 -04001083 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001084 }
1085 }
1086 fIndentation--;
1087 this->writeLine("}");
1088
1089 fOut = oldOut;
1090 this->write(fFunctionHeader);
1091 this->write(buffer.str());
1092}
1093
1094void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1095 bool globalContext) {
1096 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1097 this->write("thread ");
1098 }
1099 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001100 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001101 }
1102}
1103
1104void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1105 if ("sk_PerVertex" == intf.fTypeName) {
1106 return;
1107 }
1108 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001109 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001110 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001111 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001112 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -04001113 while (Type::kArray_Kind == structType->kind()) {
1114 structType = &structType->componentType();
1115 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001116 fIndentation++;
1117 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001118 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001119 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001120 }
1121 fIndentation--;
1122 this->write("}");
1123 if (intf.fInstanceName.size()) {
1124 this->write(" ");
1125 this->write(intf.fInstanceName);
1126 for (const auto& size : intf.fSizes) {
1127 this->write("[");
1128 if (size) {
1129 this->writeExpression(*size, kTopLevel_Precedence);
1130 }
1131 this->write("]");
1132 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001133 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1134 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001135 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001136 }
1137 this->writeLine(";");
1138}
1139
Timothy Liangdc89f192018-06-13 09:20:31 -04001140void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1141 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001142 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001143 int currentOffset = 0;
1144 for (const auto& field: fields) {
1145 int fieldOffset = field.fModifiers.fLayout.fOffset;
1146 const Type* fieldType = field.fType;
1147 if (fieldOffset != -1) {
1148 if (currentOffset > fieldOffset) {
1149 fErrors.error(parentOffset,
1150 "offset of field '" + field.fName + "' must be at least " +
1151 to_string((int) currentOffset));
1152 } else if (currentOffset < fieldOffset) {
1153 this->write("char pad");
1154 this->write(to_string(fPaddingCount++));
1155 this->write("[");
1156 this->write(to_string(fieldOffset - currentOffset));
1157 this->writeLine("];");
1158 currentOffset = fieldOffset;
1159 }
1160 int alignment = memoryLayout.alignment(*fieldType);
1161 if (fieldOffset % alignment) {
1162 fErrors.error(parentOffset,
1163 "offset of field '" + field.fName + "' must be a multiple of " +
1164 to_string((int) alignment));
1165 }
1166 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001167 currentOffset += memoryLayout.size(*fieldType);
1168 std::vector<int> sizes;
1169 while (fieldType->kind() == Type::kArray_Kind) {
1170 sizes.push_back(fieldType->columns());
1171 fieldType = &fieldType->componentType();
1172 }
1173 this->writeModifiers(field.fModifiers, false);
1174 this->writeType(*fieldType);
1175 this->write(" ");
1176 this->writeName(field.fName);
1177 for (int s : sizes) {
1178 if (s <= 0) {
1179 this->write("[]");
1180 } else {
1181 this->write("[" + to_string(s) + "]");
1182 }
1183 }
1184 this->writeLine(";");
1185 if (parentIntf) {
1186 fInterfaceBlockMap[&field] = parentIntf;
1187 }
1188 }
1189}
1190
Ethan Nicholascc305772017-10-13 16:17:45 -04001191void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1192 this->writeExpression(value, kTopLevel_Precedence);
1193}
1194
Timothy Liang651286f2018-06-07 09:55:33 -04001195void MetalCodeGenerator::writeName(const String& name) {
1196 if (fReservedWords.find(name) != fReservedWords.end()) {
1197 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1198 }
1199 this->write(name);
1200}
1201
Ethan Nicholascc305772017-10-13 16:17:45 -04001202void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001203 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001204 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001205 for (const auto& stmt : decl.fVars) {
1206 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001207 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001208 continue;
1209 }
1210 if (wroteType) {
1211 this->write(", ");
1212 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001213 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001214 this->writeType(decl.fBaseType);
1215 this->write(" ");
1216 wroteType = true;
1217 }
Timothy Liang651286f2018-06-07 09:55:33 -04001218 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001219 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001220 this->write("[");
1221 if (size) {
1222 this->writeExpression(*size, kTopLevel_Precedence);
1223 }
1224 this->write("]");
1225 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001226 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001227 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001228 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001229 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001230 }
1231 if (wroteType) {
1232 this->write(";");
1233 }
1234}
1235
1236void MetalCodeGenerator::writeStatement(const Statement& s) {
1237 switch (s.fKind) {
1238 case Statement::kBlock_Kind:
1239 this->writeBlock((Block&) s);
1240 break;
1241 case Statement::kExpression_Kind:
1242 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1243 this->write(";");
1244 break;
1245 case Statement::kReturn_Kind:
1246 this->writeReturnStatement((ReturnStatement&) s);
1247 break;
1248 case Statement::kVarDeclarations_Kind:
1249 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1250 break;
1251 case Statement::kIf_Kind:
1252 this->writeIfStatement((IfStatement&) s);
1253 break;
1254 case Statement::kFor_Kind:
1255 this->writeForStatement((ForStatement&) s);
1256 break;
1257 case Statement::kWhile_Kind:
1258 this->writeWhileStatement((WhileStatement&) s);
1259 break;
1260 case Statement::kDo_Kind:
1261 this->writeDoStatement((DoStatement&) s);
1262 break;
1263 case Statement::kSwitch_Kind:
1264 this->writeSwitchStatement((SwitchStatement&) s);
1265 break;
1266 case Statement::kBreak_Kind:
1267 this->write("break;");
1268 break;
1269 case Statement::kContinue_Kind:
1270 this->write("continue;");
1271 break;
1272 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001273 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001274 break;
1275 case Statement::kNop_Kind:
1276 this->write(";");
1277 break;
1278 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001279#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001280 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001281#endif
1282 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001283 }
1284}
1285
1286void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1287 for (const auto& s : statements) {
1288 if (!s->isEmpty()) {
1289 this->writeStatement(*s);
1290 this->writeLine();
1291 }
1292 }
1293}
1294
1295void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001296 if (b.fIsScope) {
1297 this->writeLine("{");
1298 fIndentation++;
1299 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001300 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001301 if (b.fIsScope) {
1302 fIndentation--;
1303 this->write("}");
1304 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001305}
1306
1307void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1308 this->write("if (");
1309 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1310 this->write(") ");
1311 this->writeStatement(*stmt.fIfTrue);
1312 if (stmt.fIfFalse) {
1313 this->write(" else ");
1314 this->writeStatement(*stmt.fIfFalse);
1315 }
1316}
1317
1318void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1319 this->write("for (");
1320 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1321 this->writeStatement(*f.fInitializer);
1322 } else {
1323 this->write("; ");
1324 }
1325 if (f.fTest) {
1326 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1327 }
1328 this->write("; ");
1329 if (f.fNext) {
1330 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1331 }
1332 this->write(") ");
1333 this->writeStatement(*f.fStatement);
1334}
1335
1336void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1337 this->write("while (");
1338 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1339 this->write(") ");
1340 this->writeStatement(*w.fStatement);
1341}
1342
1343void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1344 this->write("do ");
1345 this->writeStatement(*d.fStatement);
1346 this->write(" while (");
1347 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1348 this->write(");");
1349}
1350
1351void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1352 this->write("switch (");
1353 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1354 this->writeLine(") {");
1355 fIndentation++;
1356 for (const auto& c : s.fCases) {
1357 if (c->fValue) {
1358 this->write("case ");
1359 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1360 this->writeLine(":");
1361 } else {
1362 this->writeLine("default:");
1363 }
1364 fIndentation++;
1365 for (const auto& stmt : c->fStatements) {
1366 this->writeStatement(*stmt);
1367 this->writeLine();
1368 }
1369 fIndentation--;
1370 }
1371 fIndentation--;
1372 this->write("}");
1373}
1374
1375void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1376 this->write("return");
1377 if (r.fExpression) {
1378 this->write(" ");
1379 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1380 }
1381 this->write(";");
1382}
1383
1384void MetalCodeGenerator::writeHeader() {
1385 this->write("#include <metal_stdlib>\n");
1386 this->write("#include <simd/simd.h>\n");
1387 this->write("using namespace metal;\n");
1388}
1389
1390void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001391 for (const auto& e : fProgram) {
1392 if (ProgramElement::kVar_Kind == e.fKind) {
1393 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001394 if (!decls.fVars.size()) {
1395 continue;
1396 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001397 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001398 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1399 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001400 if (-1 == fUniformBuffer) {
1401 this->write("struct Uniforms {\n");
1402 fUniformBuffer = first.fModifiers.fLayout.fSet;
1403 if (-1 == fUniformBuffer) {
1404 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1405 }
1406 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1407 if (-1 == fUniformBuffer) {
1408 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1409 "the same 'layout(set=...)'");
1410 }
1411 }
1412 this->write(" ");
1413 this->writeType(first.fType);
1414 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001415 for (const auto& stmt : decls.fVars) {
1416 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001417 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001418 }
1419 this->write(";\n");
1420 }
1421 }
1422 }
1423 if (-1 != fUniformBuffer) {
1424 this->write("};\n");
1425 }
1426}
1427
1428void MetalCodeGenerator::writeInputStruct() {
1429 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001430 for (const auto& e : fProgram) {
1431 if (ProgramElement::kVar_Kind == e.fKind) {
1432 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001433 if (!decls.fVars.size()) {
1434 continue;
1435 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001436 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001437 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1438 -1 == first.fModifiers.fLayout.fBuiltin) {
1439 this->write(" ");
1440 this->writeType(first.fType);
1441 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001442 for (const auto& stmt : decls.fVars) {
1443 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001444 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001445 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001446 if (fProgram.fKind == Program::kVertex_Kind) {
1447 this->write(" [[attribute(" +
1448 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1449 } else if (fProgram.fKind == Program::kFragment_Kind) {
1450 this->write(" [[user(locn" +
1451 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1452 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001453 }
1454 }
1455 this->write(";\n");
1456 }
1457 }
1458 }
1459 this->write("};\n");
1460}
1461
1462void MetalCodeGenerator::writeOutputStruct() {
1463 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001464 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001465 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001466 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001467 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001468 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001469 for (const auto& e : fProgram) {
1470 if (ProgramElement::kVar_Kind == e.fKind) {
1471 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001472 if (!decls.fVars.size()) {
1473 continue;
1474 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001475 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001476 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1477 -1 == first.fModifiers.fLayout.fBuiltin) {
1478 this->write(" ");
1479 this->writeType(first.fType);
1480 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001481 for (const auto& stmt : decls.fVars) {
1482 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001483 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001484 if (fProgram.fKind == Program::kVertex_Kind) {
1485 this->write(" [[user(locn" +
1486 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1487 } else if (fProgram.fKind == Program::kFragment_Kind) {
1488 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001489 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1490 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1491 if (colorIndex) {
1492 this->write(", index(" + to_string(colorIndex) + ")");
1493 }
1494 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001495 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001496 }
1497 this->write(";\n");
1498 }
1499 }
Timothy Liang7d637782018-06-05 09:58:07 -04001500 }
1501 if (fProgram.fKind == Program::kVertex_Kind) {
1502 this->write(" float sk_PointSize;\n");
1503 }
1504 this->write("};\n");
1505}
1506
1507void MetalCodeGenerator::writeInterfaceBlocks() {
1508 bool wroteInterfaceBlock = false;
1509 for (const auto& e : fProgram) {
1510 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1511 this->writeInterfaceBlock((InterfaceBlock&) e);
1512 wroteInterfaceBlock = true;
1513 }
1514 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001515 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001516 this->writeLine("struct sksl_synthetic_uniforms {");
1517 this->writeLine(" float u_skRTHeight;");
1518 this->writeLine("};");
1519 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001520}
1521
John Stilescdcdb042020-07-06 09:03:51 -04001522void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1523 // Visit the interface blocks.
1524 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1525 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1526 }
1527 for (const ProgramElement& element : fProgram) {
1528 if (element.fKind != ProgramElement::kVar_Kind) {
1529 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001530 }
John Stilescdcdb042020-07-06 09:03:51 -04001531 const VarDeclarations& decls = static_cast<const VarDeclarations&>(element);
1532 if (decls.fVars.empty()) {
1533 continue;
1534 }
1535 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
1536 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1537 first.fType.kind() == Type::kSampler_Kind) {
1538 for (const auto& stmt : decls.fVars) {
1539 VarDeclaration& var = static_cast<VarDeclaration&>(*stmt);
John Stilesc67b3622020-05-28 17:53:13 -04001540
John Stilescdcdb042020-07-06 09:03:51 -04001541 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1542 // Samplers are represented as a "texture/sampler" duo in the global struct.
1543 visitor->VisitTexture(first.fType, var.fVar->fName);
1544 visitor->VisitSampler(first.fType, String(var.fVar->fName) + SAMPLER_SUFFIX);
1545 } else {
1546 // Visit a regular variable.
1547 visitor->VisitVariable(*var.fVar, var.fValue.get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001548 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001549 }
1550 }
1551 }
John Stilescdcdb042020-07-06 09:03:51 -04001552}
1553
1554void MetalCodeGenerator::writeGlobalStruct() {
1555 class : public GlobalStructVisitor {
1556 public:
1557 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1558 this->AddElement();
1559 fCodeGen->write(" constant ");
1560 fCodeGen->write(block.fTypeName);
1561 fCodeGen->write("* ");
1562 fCodeGen->writeName(blockName);
1563 fCodeGen->write(";\n");
1564 }
1565 void VisitTexture(const Type& type, const String& name) override {
1566 this->AddElement();
1567 fCodeGen->write(" ");
1568 fCodeGen->writeType(type);
1569 fCodeGen->write(" ");
1570 fCodeGen->writeName(name);
1571 fCodeGen->write(";\n");
1572 }
1573 void VisitSampler(const Type&, const String& name) override {
1574 this->AddElement();
1575 fCodeGen->write(" sampler ");
1576 fCodeGen->writeName(name);
1577 fCodeGen->write(";\n");
1578 }
1579 void VisitVariable(const Variable& var, const Expression* value) override {
1580 this->AddElement();
1581 fCodeGen->write(" ");
1582 fCodeGen->writeType(var.fType);
1583 fCodeGen->write(" ");
1584 fCodeGen->writeName(var.fName);
1585 fCodeGen->write(";\n");
1586 }
1587 void AddElement() {
1588 if (fFirst) {
1589 fCodeGen->write("struct Globals {\n");
1590 fFirst = false;
1591 }
1592 }
1593 void Finish() {
1594 if (!fFirst) {
1595 fCodeGen->write("};");
1596 fFirst = true;
1597 }
1598 }
1599
1600 MetalCodeGenerator* fCodeGen = nullptr;
1601 bool fFirst = true;
1602 } visitor;
1603
1604 visitor.fCodeGen = this;
1605 this->visitGlobalStruct(&visitor);
1606 visitor.Finish();
1607}
1608
1609void MetalCodeGenerator::writeGlobalInit() {
1610 class : public GlobalStructVisitor {
1611 public:
1612 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1613 const String& blockName) override {
1614 this->AddElement();
1615 fCodeGen->write("&");
1616 fCodeGen->writeName(blockName);
1617 }
1618 void VisitTexture(const Type&, const String& name) override {
1619 this->AddElement();
1620 fCodeGen->writeName(name);
1621 }
1622 void VisitSampler(const Type&, const String& name) override {
1623 this->AddElement();
1624 fCodeGen->writeName(name);
1625 }
1626 void VisitVariable(const Variable& var, const Expression* value) override {
1627 this->AddElement();
1628 if (value) {
1629 fCodeGen->writeVarInitializer(var, *value);
1630 } else {
1631 fCodeGen->write("{}");
1632 }
1633 }
1634 void AddElement() {
1635 if (fFirst) {
1636 fCodeGen->write(" Globals globalStruct{");
1637 fFirst = false;
1638 } else {
1639 fCodeGen->write(", ");
1640 }
1641 }
1642 void Finish() {
1643 if (!fFirst) {
1644 fCodeGen->writeLine("};");
1645 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1646 fCodeGen->writeLine(" (void)_globals;");
1647 }
1648 }
1649 MetalCodeGenerator* fCodeGen = nullptr;
1650 bool fFirst = true;
1651 } visitor;
1652
1653 visitor.fCodeGen = this;
1654 this->visitGlobalStruct(&visitor);
1655 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001656}
1657
Ethan Nicholascc305772017-10-13 16:17:45 -04001658void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1659 switch (e.fKind) {
1660 case ProgramElement::kExtension_Kind:
1661 break;
1662 case ProgramElement::kVar_Kind: {
1663 VarDeclarations& decl = (VarDeclarations&) e;
1664 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001665 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001666 if (-1 == builtin) {
1667 // normal var
1668 this->writeVarDeclarations(decl, true);
1669 this->writeLine();
1670 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1671 // ignore
1672 }
1673 }
1674 break;
1675 }
1676 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001677 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 break;
1679 case ProgramElement::kFunction_Kind:
1680 this->writeFunction((FunctionDefinition&) e);
1681 break;
1682 case ProgramElement::kModifiers_Kind:
1683 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1684 this->writeLine(";");
1685 break;
1686 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001687#ifdef SK_DEBUG
1688 ABORT("unsupported program element: %s\n", e.description().c_str());
1689#endif
1690 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001691 }
1692}
1693
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001694MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1695 if (!e) {
1696 return kNo_Requirements;
1697 }
1698 switch (e->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001699 case Expression::kFunctionCall_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001700 const FunctionCall& f = (const FunctionCall&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001701 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001702 for (const auto& arg : f.fArguments) {
1703 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001704 }
1705 return result;
1706 }
1707 case Expression::kConstructor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001708 const Constructor& c = (const Constructor&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001709 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001710 for (const auto& arg : c.fArguments) {
1711 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001712 }
1713 return result;
1714 }
Timothy Liang7d637782018-06-05 09:58:07 -04001715 case Expression::kFieldAccess_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001716 const FieldAccess& f = (const FieldAccess&) *e;
Timothy Liang7d637782018-06-05 09:58:07 -04001717 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1718 return kGlobals_Requirement;
1719 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001720 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001721 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001722 case Expression::kSwizzle_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001723 return this->requirements(((const Swizzle&) *e).fBase.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001724 case Expression::kBinary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001725 const BinaryExpression& b = (const BinaryExpression&) *e;
1726 return this->requirements(b.fLeft.get()) | this->requirements(b.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001727 }
1728 case Expression::kIndex_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001729 const IndexExpression& idx = (const IndexExpression&) *e;
1730 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001731 }
1732 case Expression::kPrefix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001733 return this->requirements(((const PrefixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001734 case Expression::kPostfix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001735 return this->requirements(((const PostfixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001736 case Expression::kTernary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001737 const TernaryExpression& t = (const TernaryExpression&) *e;
1738 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1739 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001740 }
1741 case Expression::kVariableReference_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001742 const VariableReference& v = (const VariableReference&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001743 Requirements result = kNo_Requirements;
1744 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001745 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001746 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1747 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1748 result = kInputs_Requirement;
1749 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1750 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001751 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1752 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001753 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001754 } else {
1755 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001756 }
1757 }
1758 return result;
1759 }
1760 default:
1761 return kNo_Requirements;
1762 }
1763}
1764
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001765MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1766 if (!s) {
1767 return kNo_Requirements;
1768 }
1769 switch (s->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001770 case Statement::kBlock_Kind: {
1771 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001772 for (const auto& child : ((const Block*) s)->fStatements) {
1773 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001774 }
1775 return result;
1776 }
Timothy Liang7d637782018-06-05 09:58:07 -04001777 case Statement::kVarDeclaration_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001778 const VarDeclaration& var = (const VarDeclaration&) *s;
1779 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001780 }
1781 case Statement::kVarDeclarations_Kind: {
1782 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001783 const VarDeclarations& decls = *((const VarDeclarationsStatement&) *s).fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001784 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001785 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001786 }
1787 return result;
1788 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001789 case Statement::kExpression_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001790 return this->requirements(((const ExpressionStatement&) *s).fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001791 case Statement::kReturn_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001792 const ReturnStatement& r = (const ReturnStatement&) *s;
1793 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 }
1795 case Statement::kIf_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001796 const IfStatement& i = (const IfStatement&) *s;
1797 return this->requirements(i.fTest.get()) |
1798 this->requirements(i.fIfTrue.get()) |
1799 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001800 }
1801 case Statement::kFor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001802 const ForStatement& f = (const ForStatement&) *s;
1803 return this->requirements(f.fInitializer.get()) |
1804 this->requirements(f.fTest.get()) |
1805 this->requirements(f.fNext.get()) |
1806 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001807 }
1808 case Statement::kWhile_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001809 const WhileStatement& w = (const WhileStatement&) *s;
1810 return this->requirements(w.fTest.get()) |
1811 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 }
1813 case Statement::kDo_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001814 const DoStatement& d = (const DoStatement&) *s;
1815 return this->requirements(d.fTest.get()) |
1816 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001817 }
1818 case Statement::kSwitch_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001819 const SwitchStatement& sw = (const SwitchStatement&) *s;
1820 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001821 for (const auto& c : sw.fCases) {
1822 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001823 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001824 }
1825 }
1826 return result;
1827 }
1828 default:
1829 return kNo_Requirements;
1830 }
1831}
1832
1833MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1834 if (f.fBuiltin) {
1835 return kNo_Requirements;
1836 }
1837 auto found = fRequirements.find(&f);
1838 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001839 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001840 for (const auto& e : fProgram) {
1841 if (ProgramElement::kFunction_Kind == e.fKind) {
1842 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001843 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001844 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001845 fRequirements[&f] = reqs;
1846 return reqs;
1847 }
1848 }
1849 }
1850 }
1851 return found->second;
1852}
1853
Timothy Liangb8eeb802018-07-23 16:46:16 -04001854bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001855 OutputStream* rawOut = fOut;
1856 fOut = &fHeader;
1857 fProgramKind = fProgram.fKind;
1858 this->writeHeader();
1859 this->writeUniformStruct();
1860 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001861 this->writeOutputStruct();
1862 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001863 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 StringStream body;
1865 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001866 for (const auto& e : fProgram) {
1867 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001868 }
1869 fOut = rawOut;
1870
1871 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001872 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001873 write_stringstream(body, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001874 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001875}
1876
John Stilesa6841be2020-08-06 14:11:56 -04001877} // namespace SkSL