blob: ad2ca45dd9c686c240b11dd7fdcee3a2b507df20 [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 Stiles1bdafbf2020-05-28 12:17:20 -0400391// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
392// Keeps track of previously generated constructors so that we won't generate more than one
393// constructor for any given permutation of input argument types. Returns the name of the
394// generated constructor method.
395String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
396 const Type& matrix = c.fType;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500397 int columns = matrix.columns();
398 int rows = matrix.rows();
John Stiles1bdafbf2020-05-28 12:17:20 -0400399 const std::vector<std::unique_ptr<Expression>>& args = c.fArguments;
400
401 // Create the helper-method name and use it as our lookup key.
402 String name;
403 name.appendf("float%dx%d_from", columns, rows);
404 for (const std::unique_ptr<Expression>& expr : args) {
405 name.appendf("_%s", expr->fType.displayName().c_str());
406 }
407
408 // If a helper-method has already been synthesized, we don't need to synthesize it again.
409 auto [iter, newlyCreated] = fHelpers.insert(name);
410 if (!newlyCreated) {
411 return name;
412 }
413
414 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
415 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
416 // supply a mixture of scalars and vectors.)
417 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
418
419 size_t argIndex = 0;
420 const char* argSeparator = "";
421 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
422 fExtraFunctions.printf("%s%s x%zu", argSeparator,
423 expr->fType.displayName().c_str(), argIndex++);
424 argSeparator = ", ";
425 }
426
427 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
428
429 argIndex = 0;
430 int argPosition = 0;
431
432 const char* columnSeparator = "";
433 for (int c = 0; c < columns; ++c) {
434 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
435 columnSeparator = "), ";
436
437 const char* rowSeparator = "";
438 for (int r = 0; r < rows; ++r) {
439 fExtraFunctions.printf("%s", rowSeparator);
440 rowSeparator = ", ";
441
442 const Type& argType = args[argIndex]->fType;
443 switch (argType.kind()) {
444 case Type::kScalar_Kind: {
445 fExtraFunctions.printf("x%zu", argIndex);
446 break;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500447 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400448 case Type::kVector_Kind: {
449 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
450 break;
451 }
452 case Type::kMatrix_Kind: {
453 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
454 argPosition / argType.rows(),
455 argPosition % argType.rows());
456 break;
457 }
458 default: {
459 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
460 fExtraFunctions.printf("<error>");
461 break;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500462 }
463 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400464
465 ++argPosition;
466 if (argPosition >= argType.columns() * argType.rows()) {
467 ++argIndex;
468 argPosition = 0;
469 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500470 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400471 }
472
473 if (argPosition != 0 || argIndex != args.size()) {
474 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500475 name = "<error>";
476 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400477
478 fExtraFunctions.printf("));\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500479 return name;
480}
481
482bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
483 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
484 return false;
485 }
486 if (t1.columns() > 1) {
487 return this->canCoerce(t1.componentType(), t2.componentType());
488 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500489 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500490}
491
John Stiles1bdafbf2020-05-28 12:17:20 -0400492bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
493 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
494 if (c.fType.kind() != Type::kMatrix_Kind) {
495 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500496 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400497
498 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
499 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
500 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
501 // scalars can be constructed trivially. In more complex cases, we generate a helper function
502 // that converts our inputs into a properly-shaped matrix.
503 // A matrix construct helper method is always used if any input argument is a matrix.
504 // Helper methods are also necessary when any argument would span multiple rows. For instance:
505 //
506 // float2 x = (1, 2);
507 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
508 // | 2 4 6 |
509 //
510 // float2 x = (2, 3);
511 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
512 // | 2 4 6 |
513 //
514 // float4 x = (1, 2, 3, 4);
515 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
516 // | 2 4 |
517 //
518
519 int position = 0;
520 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
521 // If an input argument is a matrix, we need a helper function.
522 if (expr->fType.kind() == Type::kMatrix_Kind) {
523 return true;
524 }
525 position += expr->fType.columns();
526 if (position > c.fType.rows()) {
527 // An input argument would span multiple rows; a helper function is required.
528 return true;
529 }
530 if (position == c.fType.rows()) {
531 // We've advanced to the end of a row. Wrap to the start of the next row.
532 position = 0;
533 }
534 }
535
536 return false;
537}
538
539void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
540 // Handle special cases for single-argument constructors.
541 if (c.fArguments.size() == 1) {
542 // If the type is coercible, emit it directly.
543 const Expression& arg = *c.fArguments.front();
544 if (this->canCoerce(c.fType, arg.fType)) {
545 this->writeExpression(arg, parentPrecedence);
546 return;
547 }
548
549 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
550 // matrix constructor.
551 if (c.fType.kind() == Type::kMatrix_Kind && arg.fType.isNumber()) {
552 const Type& matrix = c.fType;
553 this->write("float");
554 this->write(to_string(matrix.columns()));
555 this->write("x");
556 this->write(to_string(matrix.rows()));
557 this->write("(");
558 this->writeExpression(arg, parentPrecedence);
559 this->write(")");
560 return;
561 }
562 }
563
564 // Emit and invoke a matrix-constructor helper method if one is necessary.
565 if (this->matrixConstructHelperIsNeeded(c)) {
566 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000567 this->write("(");
568 const char* separator = "";
John Stiles1bdafbf2020-05-28 12:17:20 -0400569 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
John Stiles1fa15b12020-05-28 17:36:54 +0000570 this->write(separator);
571 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400572 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400573 }
John Stiles1fa15b12020-05-28 17:36:54 +0000574 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400575 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400576 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400577
578 // Explicitly invoke the constructor, passing in the necessary arguments.
579 this->writeType(c.fType);
580 this->write("(");
581 const char* separator = "";
582 int scalarCount = 0;
583 for (const std::unique_ptr<Expression>& arg : c.fArguments) {
584 this->write(separator);
585 separator = ", ";
586 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() < c.fType.rows()) {
587 // Merge scalars and smaller vectors together.
588 if (!scalarCount) {
589 this->writeType(c.fType.componentType());
590 this->write(to_string(c.fType.rows()));
591 this->write("(");
592 }
593 scalarCount += arg->fType.columns();
594 }
595 this->writeExpression(*arg, kSequence_Precedence);
596 if (scalarCount && scalarCount == c.fType.rows()) {
597 this->write(")");
598 scalarCount = 0;
599 }
600 }
601 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400602}
603
604void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400605 if (fRTHeightName.length()) {
606 this->write("float4(_fragCoord.x, ");
607 this->write(fRTHeightName.c_str());
608 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500609 } else {
610 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
611 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400612}
613
614void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
615 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
616 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400617 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400618 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400619 case SK_FRAGCOORD_BUILTIN:
620 this->writeFragCoord();
621 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400622 case SK_VERTEXID_BUILTIN:
623 this->write("sk_VertexID");
624 break;
625 case SK_INSTANCEID_BUILTIN:
626 this->write("sk_InstanceID");
627 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400628 case SK_CLOCKWISE_BUILTIN:
629 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400630 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400631 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
632 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400633 default:
634 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
635 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
636 this->write("_in.");
637 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400638 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400639 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
640 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400641 this->write("_uniforms.");
642 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400643 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400644 }
645 }
Timothy Liang651286f2018-06-07 09:55:33 -0400646 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400647 }
648}
649
650void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
651 this->writeExpression(*expr.fBase, kPostfix_Precedence);
652 this->write("[");
653 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
654 this->write("]");
655}
656
657void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400658 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400659 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
660 this->writeExpression(*f.fBase, kPostfix_Precedence);
661 this->write(".");
662 }
Timothy Liang7d637782018-06-05 09:58:07 -0400663 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400664 case SK_CLIPDISTANCE_BUILTIN:
665 this->write("gl_ClipDistance");
666 break;
667 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400668 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400669 break;
670 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400671 if (field->fName == "sk_PointSize") {
672 this->write("_out->sk_PointSize");
673 } else {
674 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
675 this->write("_globals->");
676 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
677 this->write("->");
678 }
Timothy Liang651286f2018-06-07 09:55:33 -0400679 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400680 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400681 }
682}
683
684void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500685 int last = swizzle.fComponents.back();
686 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
687 this->writeType(swizzle.fType);
688 this->write("(");
689 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400690 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
691 this->write(".");
692 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500693 if (c >= 0) {
694 this->write(&("x\0y\0z\0w\0"[c * 2]));
695 }
696 }
697 if (last == SKSL_SWIZZLE_0) {
698 this->write(", 0)");
699 }
700 else if (last == SKSL_SWIZZLE_1) {
701 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400702 }
703}
704
705MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
706 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400707 case Token::Kind::TK_STAR: // fall through
708 case Token::Kind::TK_SLASH: // fall through
709 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
710 case Token::Kind::TK_PLUS: // fall through
711 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
712 case Token::Kind::TK_SHL: // fall through
713 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
714 case Token::Kind::TK_LT: // fall through
715 case Token::Kind::TK_GT: // fall through
716 case Token::Kind::TK_LTEQ: // fall through
717 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
718 case Token::Kind::TK_EQEQ: // fall through
719 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
720 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
721 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
722 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
723 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
724 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
725 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
726 case Token::Kind::TK_EQ: // fall through
727 case Token::Kind::TK_PLUSEQ: // fall through
728 case Token::Kind::TK_MINUSEQ: // fall through
729 case Token::Kind::TK_STAREQ: // fall through
730 case Token::Kind::TK_SLASHEQ: // fall through
731 case Token::Kind::TK_PERCENTEQ: // fall through
732 case Token::Kind::TK_SHLEQ: // fall through
733 case Token::Kind::TK_SHREQ: // fall through
734 case Token::Kind::TK_LOGICALANDEQ: // fall through
735 case Token::Kind::TK_LOGICALXOREQ: // fall through
736 case Token::Kind::TK_LOGICALOREQ: // fall through
737 case Token::Kind::TK_BITWISEANDEQ: // fall through
738 case Token::Kind::TK_BITWISEXOREQ: // fall through
739 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
740 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400741 default: ABORT("unsupported binary operator");
742 }
743}
744
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500745void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
746 const Type& result) {
747 String key = "TimesEqual" + left.name() + right.name();
748 if (fHelpers.find(key) == fHelpers.end()) {
749 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
750 " left = left * right;\n"
751 " return left;\n"
752 "}", result.name().c_str(), left.name().c_str(),
753 right.name().c_str());
754 }
755}
756
Ethan Nicholascc305772017-10-13 16:17:45 -0400757void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
758 Precedence parentPrecedence) {
759 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500760 bool needParens = precedence >= parentPrecedence;
761 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400762 case Token::Kind::TK_EQEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500763 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
764 this->write("all");
765 needParens = true;
766 }
767 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400768 case Token::Kind::TK_NEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500769 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400770 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500771 needParens = true;
772 }
773 break;
774 default:
775 break;
776 }
777 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400778 this->write("(");
779 }
780 if (Compiler::IsAssignment(b.fOperator) &&
781 Expression::kVariableReference_Kind == b.fLeft->fKind &&
782 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
783 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
784 // writing to an out parameter. Since we have to turn those into pointers, we have to
785 // dereference it here.
786 this->write("*");
787 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400788 if (b.fOperator == Token::Kind::TK_STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500789 b.fRight->fType.kind() == Type::kMatrix_Kind) {
790 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
791 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400792 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400793 if (b.fOperator != Token::Kind::TK_EQ && Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholascc305772017-10-13 16:17:45 -0400794 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
795 // This doesn't compile in Metal:
796 // float4 x = float4(1);
797 // x.xy *= float2x2(...);
798 // with the error message "non-const reference cannot bind to vector element",
799 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
800 // as long as the LHS has no side effects, and hope for the best otherwise.
801 this->write(" = ");
802 this->writeExpression(*b.fLeft, kAssignment_Precedence);
803 this->write(" ");
804 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400805 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400806 this->write(op.substr(0, op.size() - 1).c_str());
807 this->write(" ");
808 } else {
809 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
810 }
811 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500812 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400813 this->write(")");
814 }
815}
816
817void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
818 Precedence parentPrecedence) {
819 if (kTernary_Precedence >= parentPrecedence) {
820 this->write("(");
821 }
822 this->writeExpression(*t.fTest, kTernary_Precedence);
823 this->write(" ? ");
824 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
825 this->write(" : ");
826 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
827 if (kTernary_Precedence >= parentPrecedence) {
828 this->write(")");
829 }
830}
831
832void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
833 Precedence parentPrecedence) {
834 if (kPrefix_Precedence >= parentPrecedence) {
835 this->write("(");
836 }
837 this->write(Compiler::OperatorName(p.fOperator));
838 this->writeExpression(*p.fOperand, kPrefix_Precedence);
839 if (kPrefix_Precedence >= parentPrecedence) {
840 this->write(")");
841 }
842}
843
844void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
845 Precedence parentPrecedence) {
846 if (kPostfix_Precedence >= parentPrecedence) {
847 this->write("(");
848 }
849 this->writeExpression(*p.fOperand, kPostfix_Precedence);
850 this->write(Compiler::OperatorName(p.fOperator));
851 if (kPostfix_Precedence >= parentPrecedence) {
852 this->write(")");
853 }
854}
855
856void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
857 this->write(b.fValue ? "true" : "false");
858}
859
860void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
861 if (i.fType == *fContext.fUInt_Type) {
862 this->write(to_string(i.fValue & 0xffffffff) + "u");
863 } else {
864 this->write(to_string((int32_t) i.fValue));
865 }
866}
867
868void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
869 this->write(to_string(f.fValue));
870}
871
872void MetalCodeGenerator::writeSetting(const Setting& s) {
873 ABORT("internal error; setting was not folded to a constant during compilation\n");
874}
875
876void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400877 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400878 const char* separator = "";
879 if ("main" == f.fDeclaration.fName) {
880 switch (fProgram.fKind) {
881 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400882 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400883 break;
884 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400885 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400886 break;
887 default:
John Stilesf7d70432020-05-28 15:46:38 -0400888 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -0400889 }
890 this->write("(Inputs _in [[stage_in]]");
891 if (-1 != fUniformBuffer) {
892 this->write(", constant Uniforms& _uniforms [[buffer(" +
893 to_string(fUniformBuffer) + ")]]");
894 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400895 for (const auto& e : fProgram) {
896 if (ProgramElement::kVar_Kind == e.fKind) {
897 VarDeclarations& decls = (VarDeclarations&) e;
898 if (!decls.fVars.size()) {
899 continue;
900 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400901 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400902 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400903 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
John Stiles08cb2c12020-07-06 10:18:49 -0400904 if (var.fVar->fModifiers.fLayout.fBinding < 0) {
905 fErrors.error(decls.fOffset,
906 "Metal samplers must have 'layout(binding=...)'");
907 }
Timothy Liang7d637782018-06-05 09:58:07 -0400908 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400909 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400910 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400911 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
912 this->write(")]]");
913 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400914 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400915 this->write(SAMPLER_SUFFIX);
916 this->write("[[sampler(");
917 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400918 this->write(")]]");
919 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400920 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400921 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
922 InterfaceBlock& intf = (InterfaceBlock&) e;
923 if ("sk_PerVertex" == intf.fTypeName) {
924 continue;
925 }
926 this->write(", constant ");
927 this->writeType(intf.fVariable.fType);
928 this->write("& " );
929 this->write(fInterfaceBlockNameMap[&intf]);
930 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400931 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400932 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400933 }
934 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500935 if (fProgram.fKind == Program::kFragment_Kind) {
936 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400937 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400938 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400939 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400940 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400941 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400942 } else if (fProgram.fKind == Program::kVertex_Kind) {
943 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400944 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400945 separator = ", ";
946 } else {
947 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400948 this->write(" ");
949 this->writeName(f.fDeclaration.fName);
950 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400951 Requirements requirements = this->requirements(f.fDeclaration);
952 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400953 this->write("Inputs _in");
954 separator = ", ";
955 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400956 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400957 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400958 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400959 separator = ", ";
960 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400961 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400962 this->write(separator);
963 this->write("Uniforms _uniforms");
964 separator = ", ";
965 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400966 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400967 this->write(separator);
968 this->write("thread Globals* _globals");
969 separator = ", ";
970 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400971 if (requirements & kFragCoord_Requirement) {
972 this->write(separator);
973 this->write("float4 _fragCoord");
974 separator = ", ";
975 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400976 }
977 for (const auto& param : f.fDeclaration.fParameters) {
978 this->write(separator);
979 separator = ", ";
980 this->writeModifiers(param->fModifiers, false);
981 std::vector<int> sizes;
982 const Type* type = &param->fType;
983 while (Type::kArray_Kind == type->kind()) {
984 sizes.push_back(type->columns());
985 type = &type->componentType();
986 }
987 this->writeType(*type);
988 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
989 this->write("*");
990 }
Timothy Liang651286f2018-06-07 09:55:33 -0400991 this->write(" ");
992 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400993 for (int s : sizes) {
994 if (s <= 0) {
995 this->write("[]");
996 } else {
997 this->write("[" + to_string(s) + "]");
998 }
999 }
1000 }
1001 this->writeLine(") {");
1002
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001003 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001004
Ethan Nicholascc305772017-10-13 16:17:45 -04001005 if ("main" == f.fDeclaration.fName) {
John Stilescdcdb042020-07-06 09:03:51 -04001006 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001007 this->writeLine(" Outputs _outputStruct;");
1008 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001009 }
John Stilesc67b3622020-05-28 17:53:13 -04001010
Ethan Nicholascc305772017-10-13 16:17:45 -04001011 fFunctionHeader = "";
1012 OutputStream* oldOut = fOut;
1013 StringStream buffer;
1014 fOut = &buffer;
1015 fIndentation++;
1016 this->writeStatements(((Block&) *f.fBody).fStatements);
1017 if ("main" == f.fDeclaration.fName) {
1018 switch (fProgram.fKind) {
1019 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001020 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001021 break;
1022 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001023 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001024 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001025 break;
1026 default:
John Stilesf7d70432020-05-28 15:46:38 -04001027 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001028 }
1029 }
1030 fIndentation--;
1031 this->writeLine("}");
1032
1033 fOut = oldOut;
1034 this->write(fFunctionHeader);
1035 this->write(buffer.str());
1036}
1037
1038void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1039 bool globalContext) {
1040 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1041 this->write("thread ");
1042 }
1043 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001044 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001045 }
1046}
1047
1048void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1049 if ("sk_PerVertex" == intf.fTypeName) {
1050 return;
1051 }
1052 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001053 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001054 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001055 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001056 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -04001057 while (Type::kArray_Kind == structType->kind()) {
1058 structType = &structType->componentType();
1059 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001060 fIndentation++;
1061 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001062 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001063 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001064 }
1065 fIndentation--;
1066 this->write("}");
1067 if (intf.fInstanceName.size()) {
1068 this->write(" ");
1069 this->write(intf.fInstanceName);
1070 for (const auto& size : intf.fSizes) {
1071 this->write("[");
1072 if (size) {
1073 this->writeExpression(*size, kTopLevel_Precedence);
1074 }
1075 this->write("]");
1076 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001077 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1078 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001079 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001080 }
1081 this->writeLine(";");
1082}
1083
Timothy Liangdc89f192018-06-13 09:20:31 -04001084void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1085 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001086 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001087 int currentOffset = 0;
1088 for (const auto& field: fields) {
1089 int fieldOffset = field.fModifiers.fLayout.fOffset;
1090 const Type* fieldType = field.fType;
1091 if (fieldOffset != -1) {
1092 if (currentOffset > fieldOffset) {
1093 fErrors.error(parentOffset,
1094 "offset of field '" + field.fName + "' must be at least " +
1095 to_string((int) currentOffset));
1096 } else if (currentOffset < fieldOffset) {
1097 this->write("char pad");
1098 this->write(to_string(fPaddingCount++));
1099 this->write("[");
1100 this->write(to_string(fieldOffset - currentOffset));
1101 this->writeLine("];");
1102 currentOffset = fieldOffset;
1103 }
1104 int alignment = memoryLayout.alignment(*fieldType);
1105 if (fieldOffset % alignment) {
1106 fErrors.error(parentOffset,
1107 "offset of field '" + field.fName + "' must be a multiple of " +
1108 to_string((int) alignment));
1109 }
1110 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001111 currentOffset += memoryLayout.size(*fieldType);
1112 std::vector<int> sizes;
1113 while (fieldType->kind() == Type::kArray_Kind) {
1114 sizes.push_back(fieldType->columns());
1115 fieldType = &fieldType->componentType();
1116 }
1117 this->writeModifiers(field.fModifiers, false);
1118 this->writeType(*fieldType);
1119 this->write(" ");
1120 this->writeName(field.fName);
1121 for (int s : sizes) {
1122 if (s <= 0) {
1123 this->write("[]");
1124 } else {
1125 this->write("[" + to_string(s) + "]");
1126 }
1127 }
1128 this->writeLine(";");
1129 if (parentIntf) {
1130 fInterfaceBlockMap[&field] = parentIntf;
1131 }
1132 }
1133}
1134
Ethan Nicholascc305772017-10-13 16:17:45 -04001135void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1136 this->writeExpression(value, kTopLevel_Precedence);
1137}
1138
Timothy Liang651286f2018-06-07 09:55:33 -04001139void MetalCodeGenerator::writeName(const String& name) {
1140 if (fReservedWords.find(name) != fReservedWords.end()) {
1141 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1142 }
1143 this->write(name);
1144}
1145
Ethan Nicholascc305772017-10-13 16:17:45 -04001146void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001147 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001148 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001149 for (const auto& stmt : decl.fVars) {
1150 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001151 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001152 continue;
1153 }
1154 if (wroteType) {
1155 this->write(", ");
1156 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001157 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 this->writeType(decl.fBaseType);
1159 this->write(" ");
1160 wroteType = true;
1161 }
Timothy Liang651286f2018-06-07 09:55:33 -04001162 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001163 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001164 this->write("[");
1165 if (size) {
1166 this->writeExpression(*size, kTopLevel_Precedence);
1167 }
1168 this->write("]");
1169 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001170 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001171 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001172 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001173 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001174 }
1175 if (wroteType) {
1176 this->write(";");
1177 }
1178}
1179
1180void MetalCodeGenerator::writeStatement(const Statement& s) {
1181 switch (s.fKind) {
1182 case Statement::kBlock_Kind:
1183 this->writeBlock((Block&) s);
1184 break;
1185 case Statement::kExpression_Kind:
1186 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1187 this->write(";");
1188 break;
1189 case Statement::kReturn_Kind:
1190 this->writeReturnStatement((ReturnStatement&) s);
1191 break;
1192 case Statement::kVarDeclarations_Kind:
1193 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1194 break;
1195 case Statement::kIf_Kind:
1196 this->writeIfStatement((IfStatement&) s);
1197 break;
1198 case Statement::kFor_Kind:
1199 this->writeForStatement((ForStatement&) s);
1200 break;
1201 case Statement::kWhile_Kind:
1202 this->writeWhileStatement((WhileStatement&) s);
1203 break;
1204 case Statement::kDo_Kind:
1205 this->writeDoStatement((DoStatement&) s);
1206 break;
1207 case Statement::kSwitch_Kind:
1208 this->writeSwitchStatement((SwitchStatement&) s);
1209 break;
1210 case Statement::kBreak_Kind:
1211 this->write("break;");
1212 break;
1213 case Statement::kContinue_Kind:
1214 this->write("continue;");
1215 break;
1216 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001217 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001218 break;
1219 case Statement::kNop_Kind:
1220 this->write(";");
1221 break;
1222 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001223#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001224 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001225#endif
1226 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001227 }
1228}
1229
1230void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1231 for (const auto& s : statements) {
1232 if (!s->isEmpty()) {
1233 this->writeStatement(*s);
1234 this->writeLine();
1235 }
1236 }
1237}
1238
1239void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001240 if (b.fIsScope) {
1241 this->writeLine("{");
1242 fIndentation++;
1243 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001244 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001245 if (b.fIsScope) {
1246 fIndentation--;
1247 this->write("}");
1248 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001249}
1250
1251void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1252 this->write("if (");
1253 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1254 this->write(") ");
1255 this->writeStatement(*stmt.fIfTrue);
1256 if (stmt.fIfFalse) {
1257 this->write(" else ");
1258 this->writeStatement(*stmt.fIfFalse);
1259 }
1260}
1261
1262void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1263 this->write("for (");
1264 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1265 this->writeStatement(*f.fInitializer);
1266 } else {
1267 this->write("; ");
1268 }
1269 if (f.fTest) {
1270 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1271 }
1272 this->write("; ");
1273 if (f.fNext) {
1274 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1275 }
1276 this->write(") ");
1277 this->writeStatement(*f.fStatement);
1278}
1279
1280void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1281 this->write("while (");
1282 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1283 this->write(") ");
1284 this->writeStatement(*w.fStatement);
1285}
1286
1287void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1288 this->write("do ");
1289 this->writeStatement(*d.fStatement);
1290 this->write(" while (");
1291 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1292 this->write(");");
1293}
1294
1295void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1296 this->write("switch (");
1297 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1298 this->writeLine(") {");
1299 fIndentation++;
1300 for (const auto& c : s.fCases) {
1301 if (c->fValue) {
1302 this->write("case ");
1303 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1304 this->writeLine(":");
1305 } else {
1306 this->writeLine("default:");
1307 }
1308 fIndentation++;
1309 for (const auto& stmt : c->fStatements) {
1310 this->writeStatement(*stmt);
1311 this->writeLine();
1312 }
1313 fIndentation--;
1314 }
1315 fIndentation--;
1316 this->write("}");
1317}
1318
1319void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1320 this->write("return");
1321 if (r.fExpression) {
1322 this->write(" ");
1323 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1324 }
1325 this->write(";");
1326}
1327
1328void MetalCodeGenerator::writeHeader() {
1329 this->write("#include <metal_stdlib>\n");
1330 this->write("#include <simd/simd.h>\n");
1331 this->write("using namespace metal;\n");
1332}
1333
1334void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001335 for (const auto& e : fProgram) {
1336 if (ProgramElement::kVar_Kind == e.fKind) {
1337 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001338 if (!decls.fVars.size()) {
1339 continue;
1340 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001341 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001342 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1343 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001344 if (-1 == fUniformBuffer) {
1345 this->write("struct Uniforms {\n");
1346 fUniformBuffer = first.fModifiers.fLayout.fSet;
1347 if (-1 == fUniformBuffer) {
1348 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1349 }
1350 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1351 if (-1 == fUniformBuffer) {
1352 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1353 "the same 'layout(set=...)'");
1354 }
1355 }
1356 this->write(" ");
1357 this->writeType(first.fType);
1358 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001359 for (const auto& stmt : decls.fVars) {
1360 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001361 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001362 }
1363 this->write(";\n");
1364 }
1365 }
1366 }
1367 if (-1 != fUniformBuffer) {
1368 this->write("};\n");
1369 }
1370}
1371
1372void MetalCodeGenerator::writeInputStruct() {
1373 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001374 for (const auto& e : fProgram) {
1375 if (ProgramElement::kVar_Kind == e.fKind) {
1376 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001377 if (!decls.fVars.size()) {
1378 continue;
1379 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001380 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001381 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1382 -1 == first.fModifiers.fLayout.fBuiltin) {
1383 this->write(" ");
1384 this->writeType(first.fType);
1385 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001386 for (const auto& stmt : decls.fVars) {
1387 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001388 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001389 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001390 if (fProgram.fKind == Program::kVertex_Kind) {
1391 this->write(" [[attribute(" +
1392 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1393 } else if (fProgram.fKind == Program::kFragment_Kind) {
1394 this->write(" [[user(locn" +
1395 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1396 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001397 }
1398 }
1399 this->write(";\n");
1400 }
1401 }
1402 }
1403 this->write("};\n");
1404}
1405
1406void MetalCodeGenerator::writeOutputStruct() {
1407 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001408 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001409 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001410 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001411 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001412 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001413 for (const auto& e : fProgram) {
1414 if (ProgramElement::kVar_Kind == e.fKind) {
1415 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001416 if (!decls.fVars.size()) {
1417 continue;
1418 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001419 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001420 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1421 -1 == first.fModifiers.fLayout.fBuiltin) {
1422 this->write(" ");
1423 this->writeType(first.fType);
1424 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001425 for (const auto& stmt : decls.fVars) {
1426 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001427 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001428 if (fProgram.fKind == Program::kVertex_Kind) {
1429 this->write(" [[user(locn" +
1430 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1431 } else if (fProgram.fKind == Program::kFragment_Kind) {
1432 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001433 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1434 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1435 if (colorIndex) {
1436 this->write(", index(" + to_string(colorIndex) + ")");
1437 }
1438 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001439 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001440 }
1441 this->write(";\n");
1442 }
1443 }
Timothy Liang7d637782018-06-05 09:58:07 -04001444 }
1445 if (fProgram.fKind == Program::kVertex_Kind) {
1446 this->write(" float sk_PointSize;\n");
1447 }
1448 this->write("};\n");
1449}
1450
1451void MetalCodeGenerator::writeInterfaceBlocks() {
1452 bool wroteInterfaceBlock = false;
1453 for (const auto& e : fProgram) {
1454 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1455 this->writeInterfaceBlock((InterfaceBlock&) e);
1456 wroteInterfaceBlock = true;
1457 }
1458 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001459 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001460 this->writeLine("struct sksl_synthetic_uniforms {");
1461 this->writeLine(" float u_skRTHeight;");
1462 this->writeLine("};");
1463 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001464}
1465
John Stilescdcdb042020-07-06 09:03:51 -04001466void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1467 // Visit the interface blocks.
1468 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1469 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1470 }
1471 for (const ProgramElement& element : fProgram) {
1472 if (element.fKind != ProgramElement::kVar_Kind) {
1473 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001474 }
John Stilescdcdb042020-07-06 09:03:51 -04001475 const VarDeclarations& decls = static_cast<const VarDeclarations&>(element);
1476 if (decls.fVars.empty()) {
1477 continue;
1478 }
1479 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
1480 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1481 first.fType.kind() == Type::kSampler_Kind) {
1482 for (const auto& stmt : decls.fVars) {
1483 VarDeclaration& var = static_cast<VarDeclaration&>(*stmt);
John Stilesc67b3622020-05-28 17:53:13 -04001484
John Stilescdcdb042020-07-06 09:03:51 -04001485 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1486 // Samplers are represented as a "texture/sampler" duo in the global struct.
1487 visitor->VisitTexture(first.fType, var.fVar->fName);
1488 visitor->VisitSampler(first.fType, String(var.fVar->fName) + SAMPLER_SUFFIX);
1489 } else {
1490 // Visit a regular variable.
1491 visitor->VisitVariable(*var.fVar, var.fValue.get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001492 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001493 }
1494 }
1495 }
John Stilescdcdb042020-07-06 09:03:51 -04001496}
1497
1498void MetalCodeGenerator::writeGlobalStruct() {
1499 class : public GlobalStructVisitor {
1500 public:
1501 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1502 this->AddElement();
1503 fCodeGen->write(" constant ");
1504 fCodeGen->write(block.fTypeName);
1505 fCodeGen->write("* ");
1506 fCodeGen->writeName(blockName);
1507 fCodeGen->write(";\n");
1508 }
1509 void VisitTexture(const Type& type, const String& name) override {
1510 this->AddElement();
1511 fCodeGen->write(" ");
1512 fCodeGen->writeType(type);
1513 fCodeGen->write(" ");
1514 fCodeGen->writeName(name);
1515 fCodeGen->write(";\n");
1516 }
1517 void VisitSampler(const Type&, const String& name) override {
1518 this->AddElement();
1519 fCodeGen->write(" sampler ");
1520 fCodeGen->writeName(name);
1521 fCodeGen->write(";\n");
1522 }
1523 void VisitVariable(const Variable& var, const Expression* value) override {
1524 this->AddElement();
1525 fCodeGen->write(" ");
1526 fCodeGen->writeType(var.fType);
1527 fCodeGen->write(" ");
1528 fCodeGen->writeName(var.fName);
1529 fCodeGen->write(";\n");
1530 }
1531 void AddElement() {
1532 if (fFirst) {
1533 fCodeGen->write("struct Globals {\n");
1534 fFirst = false;
1535 }
1536 }
1537 void Finish() {
1538 if (!fFirst) {
1539 fCodeGen->write("};");
1540 fFirst = true;
1541 }
1542 }
1543
1544 MetalCodeGenerator* fCodeGen = nullptr;
1545 bool fFirst = true;
1546 } visitor;
1547
1548 visitor.fCodeGen = this;
1549 this->visitGlobalStruct(&visitor);
1550 visitor.Finish();
1551}
1552
1553void MetalCodeGenerator::writeGlobalInit() {
1554 class : public GlobalStructVisitor {
1555 public:
1556 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1557 const String& blockName) override {
1558 this->AddElement();
1559 fCodeGen->write("&");
1560 fCodeGen->writeName(blockName);
1561 }
1562 void VisitTexture(const Type&, const String& name) override {
1563 this->AddElement();
1564 fCodeGen->writeName(name);
1565 }
1566 void VisitSampler(const Type&, const String& name) override {
1567 this->AddElement();
1568 fCodeGen->writeName(name);
1569 }
1570 void VisitVariable(const Variable& var, const Expression* value) override {
1571 this->AddElement();
1572 if (value) {
1573 fCodeGen->writeVarInitializer(var, *value);
1574 } else {
1575 fCodeGen->write("{}");
1576 }
1577 }
1578 void AddElement() {
1579 if (fFirst) {
1580 fCodeGen->write(" Globals globalStruct{");
1581 fFirst = false;
1582 } else {
1583 fCodeGen->write(", ");
1584 }
1585 }
1586 void Finish() {
1587 if (!fFirst) {
1588 fCodeGen->writeLine("};");
1589 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1590 fCodeGen->writeLine(" (void)_globals;");
1591 }
1592 }
1593 MetalCodeGenerator* fCodeGen = nullptr;
1594 bool fFirst = true;
1595 } visitor;
1596
1597 visitor.fCodeGen = this;
1598 this->visitGlobalStruct(&visitor);
1599 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001600}
1601
Ethan Nicholascc305772017-10-13 16:17:45 -04001602void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1603 switch (e.fKind) {
1604 case ProgramElement::kExtension_Kind:
1605 break;
1606 case ProgramElement::kVar_Kind: {
1607 VarDeclarations& decl = (VarDeclarations&) e;
1608 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001609 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001610 if (-1 == builtin) {
1611 // normal var
1612 this->writeVarDeclarations(decl, true);
1613 this->writeLine();
1614 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1615 // ignore
1616 }
1617 }
1618 break;
1619 }
1620 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001621 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001622 break;
1623 case ProgramElement::kFunction_Kind:
1624 this->writeFunction((FunctionDefinition&) e);
1625 break;
1626 case ProgramElement::kModifiers_Kind:
1627 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1628 this->writeLine(";");
1629 break;
1630 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001631#ifdef SK_DEBUG
1632 ABORT("unsupported program element: %s\n", e.description().c_str());
1633#endif
1634 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001635 }
1636}
1637
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001638MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1639 if (!e) {
1640 return kNo_Requirements;
1641 }
1642 switch (e->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001643 case Expression::kFunctionCall_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001644 const FunctionCall& f = (const FunctionCall&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001645 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001646 for (const auto& arg : f.fArguments) {
1647 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001648 }
1649 return result;
1650 }
1651 case Expression::kConstructor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001652 const Constructor& c = (const Constructor&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001653 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001654 for (const auto& arg : c.fArguments) {
1655 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001656 }
1657 return result;
1658 }
Timothy Liang7d637782018-06-05 09:58:07 -04001659 case Expression::kFieldAccess_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001660 const FieldAccess& f = (const FieldAccess&) *e;
Timothy Liang7d637782018-06-05 09:58:07 -04001661 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1662 return kGlobals_Requirement;
1663 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001664 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001665 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001666 case Expression::kSwizzle_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001667 return this->requirements(((const Swizzle&) *e).fBase.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001668 case Expression::kBinary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001669 const BinaryExpression& b = (const BinaryExpression&) *e;
1670 return this->requirements(b.fLeft.get()) | this->requirements(b.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001671 }
1672 case Expression::kIndex_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001673 const IndexExpression& idx = (const IndexExpression&) *e;
1674 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001675 }
1676 case Expression::kPrefix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001677 return this->requirements(((const PrefixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 case Expression::kPostfix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001679 return this->requirements(((const PostfixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001680 case Expression::kTernary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001681 const TernaryExpression& t = (const TernaryExpression&) *e;
1682 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1683 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001684 }
1685 case Expression::kVariableReference_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001686 const VariableReference& v = (const VariableReference&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001687 Requirements result = kNo_Requirements;
1688 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001689 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001690 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1691 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1692 result = kInputs_Requirement;
1693 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1694 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001695 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1696 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001697 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001698 } else {
1699 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001700 }
1701 }
1702 return result;
1703 }
1704 default:
1705 return kNo_Requirements;
1706 }
1707}
1708
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001709MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1710 if (!s) {
1711 return kNo_Requirements;
1712 }
1713 switch (s->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001714 case Statement::kBlock_Kind: {
1715 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001716 for (const auto& child : ((const Block*) s)->fStatements) {
1717 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001718 }
1719 return result;
1720 }
Timothy Liang7d637782018-06-05 09:58:07 -04001721 case Statement::kVarDeclaration_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001722 const VarDeclaration& var = (const VarDeclaration&) *s;
1723 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001724 }
1725 case Statement::kVarDeclarations_Kind: {
1726 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001727 const VarDeclarations& decls = *((const VarDeclarationsStatement&) *s).fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001728 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001729 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001730 }
1731 return result;
1732 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001733 case Statement::kExpression_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001734 return this->requirements(((const ExpressionStatement&) *s).fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001735 case Statement::kReturn_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001736 const ReturnStatement& r = (const ReturnStatement&) *s;
1737 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001738 }
1739 case Statement::kIf_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001740 const IfStatement& i = (const IfStatement&) *s;
1741 return this->requirements(i.fTest.get()) |
1742 this->requirements(i.fIfTrue.get()) |
1743 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001744 }
1745 case Statement::kFor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001746 const ForStatement& f = (const ForStatement&) *s;
1747 return this->requirements(f.fInitializer.get()) |
1748 this->requirements(f.fTest.get()) |
1749 this->requirements(f.fNext.get()) |
1750 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001751 }
1752 case Statement::kWhile_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001753 const WhileStatement& w = (const WhileStatement&) *s;
1754 return this->requirements(w.fTest.get()) |
1755 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001756 }
1757 case Statement::kDo_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001758 const DoStatement& d = (const DoStatement&) *s;
1759 return this->requirements(d.fTest.get()) |
1760 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 }
1762 case Statement::kSwitch_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001763 const SwitchStatement& sw = (const SwitchStatement&) *s;
1764 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001765 for (const auto& c : sw.fCases) {
1766 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001767 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001768 }
1769 }
1770 return result;
1771 }
1772 default:
1773 return kNo_Requirements;
1774 }
1775}
1776
1777MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1778 if (f.fBuiltin) {
1779 return kNo_Requirements;
1780 }
1781 auto found = fRequirements.find(&f);
1782 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001783 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001784 for (const auto& e : fProgram) {
1785 if (ProgramElement::kFunction_Kind == e.fKind) {
1786 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001787 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001788 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001789 fRequirements[&f] = reqs;
1790 return reqs;
1791 }
1792 }
1793 }
1794 }
1795 return found->second;
1796}
1797
Timothy Liangb8eeb802018-07-23 16:46:16 -04001798bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001799 OutputStream* rawOut = fOut;
1800 fOut = &fHeader;
1801 fProgramKind = fProgram.fKind;
1802 this->writeHeader();
1803 this->writeUniformStruct();
1804 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001805 this->writeOutputStruct();
1806 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001807 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001808 StringStream body;
1809 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001810 for (const auto& e : fProgram) {
1811 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 }
1813 fOut = rawOut;
1814
1815 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001816 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001817 write_stringstream(body, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001818 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001819}
1820
1821}