blob: 9fdee068f1f282e67116eead4021244c5a436f5c [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
Brian Osmanc262a122020-08-06 16:34:34 -040018#include <algorithm>
19
Ethan Nicholascc305772017-10-13 16:17:45 -040020namespace SkSL {
21
John Stilescdcdb042020-07-06 09:03:51 -040022class MetalCodeGenerator::GlobalStructVisitor {
23public:
24 virtual ~GlobalStructVisitor() = default;
25 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
26 virtual void VisitTexture(const Type& type, const String& name) = 0;
27 virtual void VisitSampler(const Type& type, const String& name) = 0;
28 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
29};
30
Timothy Liangee84fe12018-05-18 14:38:19 -040031void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040032#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
33#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040034 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040035 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050036 fIntrinsicMap[String("equal")] = METAL(Equal);
37 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040038 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
39 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
40 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
41 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040042}
43
Ethan Nicholascc305772017-10-13 16:17:45 -040044void MetalCodeGenerator::write(const char* s) {
45 if (!s[0]) {
46 return;
47 }
48 if (fAtLineStart) {
49 for (int i = 0; i < fIndentation; i++) {
50 fOut->writeText(" ");
51 }
52 }
53 fOut->writeText(s);
54 fAtLineStart = false;
55}
56
57void MetalCodeGenerator::writeLine(const char* s) {
58 this->write(s);
59 fOut->writeText(fLineEnding);
60 fAtLineStart = true;
61}
62
63void MetalCodeGenerator::write(const String& s) {
64 this->write(s.c_str());
65}
66
67void MetalCodeGenerator::writeLine(const String& s) {
68 this->writeLine(s.c_str());
69}
70
71void MetalCodeGenerator::writeLine() {
72 this->writeLine("");
73}
74
75void MetalCodeGenerator::writeExtension(const Extension& ext) {
76 this->writeLine("#extension " + ext.fName + " : enable");
77}
78
Ethan Nicholas45fa8102020-01-13 10:58:49 -050079String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholascc305772017-10-13 16:17:45 -040080 switch (type.kind()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040081 case Type::kVector_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050082 return this->typeName(type.componentType()) + to_string(type.columns());
Timothy Liang43d225f2018-07-19 15:27:13 -040083 case Type::kMatrix_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
85 to_string(type.rows());
Timothy Liangee84fe12018-05-18 14:38:19 -040086 case Type::kSampler_Kind:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050087 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040088 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040089 if (type == *fContext.fHalf_Type) {
90 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050091 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040092 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050093 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040094 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050095 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040096 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050097 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040098 }
Ethan Nicholascc305772017-10-13 16:17:45 -040099 }
100}
101
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500102void MetalCodeGenerator::writeType(const Type& type) {
103 if (type.kind() == Type::kStruct_Kind) {
104 for (const Type* search : fWrittenStructs) {
105 if (*search == type) {
106 // already written
107 this->write(type.name());
108 return;
109 }
110 }
111 fWrittenStructs.push_back(&type);
112 this->writeLine("struct " + type.name() + " {");
113 fIndentation++;
114 this->writeFields(type.fields(), type.fOffset);
115 fIndentation--;
116 this->write("}");
117 } else {
118 this->write(this->typeName(type));
119 }
120}
121
Ethan Nicholascc305772017-10-13 16:17:45 -0400122void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
123 switch (expr.fKind) {
124 case Expression::kBinary_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400125 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
127 case Expression::kBoolLiteral_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400128 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400129 break;
130 case Expression::kConstructor_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400131 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400132 break;
133 case Expression::kIntLiteral_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400134 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400135 break;
136 case Expression::kFieldAccess_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400137 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400138 break;
139 case Expression::kFloatLiteral_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400140 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400141 break;
142 case Expression::kFunctionCall_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400143 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400144 break;
145 case Expression::kPrefix_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400146 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400147 break;
148 case Expression::kPostfix_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400149 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400150 break;
151 case Expression::kSetting_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400152 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400153 break;
154 case Expression::kSwizzle_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400155 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400156 break;
157 case Expression::kVariableReference_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400158 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400159 break;
160 case Expression::kTernary_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400161 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400162 break;
163 case Expression::kIndex_Kind:
John Stiles81365af2020-08-18 09:24:00 -0400164 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400165 break;
166 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500167#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400168 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500169#endif
170 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400171 }
172}
173
Timothy Liang6403b0e2018-05-17 10:40:04 -0400174void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400175 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400176 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400177 Intrinsic intrinsic = i->second;
178 int32_t intrinsicId = intrinsic.second;
179 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400180 case kSpecial_IntrinsicKind:
181 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400182 break;
183 case kMetal_IntrinsicKind:
184 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
185 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500186 case kEqual_MetalIntrinsic:
187 this->write(" == ");
188 break;
189 case kNotEqual_MetalIntrinsic:
190 this->write(" != ");
191 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400192 case kLessThan_MetalIntrinsic:
193 this->write(" < ");
194 break;
195 case kLessThanEqual_MetalIntrinsic:
196 this->write(" <= ");
197 break;
198 case kGreaterThan_MetalIntrinsic:
199 this->write(" > ");
200 break;
201 case kGreaterThanEqual_MetalIntrinsic:
202 this->write(" >= ");
203 break;
204 default:
205 ABORT("unsupported metal intrinsic kind");
206 }
207 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
208 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400209 default:
210 ABORT("unsupported intrinsic kind");
211 }
212}
213
Ethan Nicholascc305772017-10-13 16:17:45 -0400214void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400215 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
216 if (entry != fIntrinsicMap.end()) {
217 this->writeIntrinsicCall(c);
218 return;
219 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400220 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
221 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400222 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
223 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500224 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
225 SkASSERT(c.fArguments.size() == 1);
226 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400227 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
228 this->write("dfdx");
229 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700230 // Flipping Y also negates the Y derivatives.
231 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400232 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400233 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400234 }
235 this->write("(");
236 const char* separator = "";
237 if (this->requirements(c.fFunction) & kInputs_Requirement) {
238 this->write("_in");
239 separator = ", ";
240 }
241 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
242 this->write(separator);
243 this->write("_out");
244 separator = ", ";
245 }
246 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
247 this->write(separator);
248 this->write("_uniforms");
249 separator = ", ";
250 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400251 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
252 this->write(separator);
253 this->write("_globals");
254 separator = ", ";
255 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400256 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
257 this->write(separator);
258 this->write("_fragCoord");
259 separator = ", ";
260 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400261 for (size_t i = 0; i < c.fArguments.size(); ++i) {
262 const Expression& arg = *c.fArguments[i];
263 this->write(separator);
264 separator = ", ";
265 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
266 this->write("&");
267 }
268 this->writeExpression(arg, kSequence_Precedence);
269 }
270 this->write(")");
271}
272
Chris Daltondba7aab2018-11-15 10:57:49 -0500273void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500274 String typeName = mat.fType.name();
275 String name = typeName + "_inverse";
276 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500277 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
278 fWrittenIntrinsics.insert(name);
279 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500280 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500281 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
282 "}"
283 ).c_str());
284 }
285 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500286 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
287 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
288 fWrittenIntrinsics.insert(name);
289 fExtraFunctions.writeText((
290 typeName + " " + name + "(" + typeName + " m) {"
291 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
292 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
293 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
294 " float b01 = a22 * a11 - a12 * a21;"
295 " float b11 = -a22 * a10 + a12 * a20;"
296 " float b21 = a21 * a10 - a11 * a20;"
297 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
298 " return " + typeName +
299 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
300 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
301 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
302 " (1/det);"
303 "}"
304 ).c_str());
305 }
306 }
307 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
308 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
309 fWrittenIntrinsics.insert(name);
310 fExtraFunctions.writeText((
311 typeName + " " + name + "(" + typeName + " m) {"
312 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
313 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
314 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
315 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
316 " float b00 = a00 * a11 - a01 * a10;"
317 " float b01 = a00 * a12 - a02 * a10;"
318 " float b02 = a00 * a13 - a03 * a10;"
319 " float b03 = a01 * a12 - a02 * a11;"
320 " float b04 = a01 * a13 - a03 * a11;"
321 " float b05 = a02 * a13 - a03 * a12;"
322 " float b06 = a20 * a31 - a21 * a30;"
323 " float b07 = a20 * a32 - a22 * a30;"
324 " float b08 = a20 * a33 - a23 * a30;"
325 " float b09 = a21 * a32 - a22 * a31;"
326 " float b10 = a21 * a33 - a23 * a31;"
327 " float b11 = a22 * a33 - a23 * a32;"
328 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
329 " b04 * b07 + b05 * b06;"
330 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
331 " a02 * b10 - a01 * b11 - a03 * b09,"
332 " a31 * b05 - a32 * b04 + a33 * b03,"
333 " a22 * b04 - a21 * b05 - a23 * b03,"
334 " a12 * b08 - a10 * b11 - a13 * b07,"
335 " a00 * b11 - a02 * b08 + a03 * b07,"
336 " a32 * b02 - a30 * b05 - a33 * b01,"
337 " a20 * b05 - a22 * b02 + a23 * b01,"
338 " a10 * b10 - a11 * b08 + a13 * b06,"
339 " a01 * b08 - a00 * b10 - a03 * b06,"
340 " a30 * b04 - a31 * b02 + a33 * b00,"
341 " a21 * b02 - a20 * b04 - a23 * b00,"
342 " a11 * b07 - a10 * b09 - a12 * b06,"
343 " a00 * b09 - a01 * b07 + a02 * b06,"
344 " a31 * b01 - a30 * b03 - a32 * b00,"
345 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
346 "}"
347 ).c_str());
348 }
349 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500350 this->write(name);
351}
352
Timothy Liang6403b0e2018-05-17 10:40:04 -0400353void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
354 switch (kind) {
355 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400356 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400357 this->write(".sample(");
358 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
359 this->write(SAMPLER_SUFFIX);
360 this->write(", ");
Timothy Liangee84fe12018-05-18 14:38:19 -0400361 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500362 // have to store the vector in a temp variable to avoid double evaluating it
363 String tmpVar = "tmpCoord" + to_string(fVarCount++);
364 this->fFunctionHeader += " " + this->typeName(c.fArguments[1]->fType) + " " +
365 tmpVar + ";\n";
366 this->write("(" + tmpVar + " = ");
367 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
368 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400369 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400370 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500371 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400372 this->write(")");
373 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400374 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500375 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400376 // 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 -0500377 String tmpX = "tmpX" + to_string(fVarCount++);
378 String tmpY = "tmpY" + to_string(fVarCount++);
379 this->fFunctionHeader += " " + this->typeName(c.fArguments[0]->fType) + " " + tmpX +
380 ", " + tmpY + ";\n";
381 this->write("(" + tmpX + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400382 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500383 this->write(", " + tmpY + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400384 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500385 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400386 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500387 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400388 default:
389 ABORT("unsupported special intrinsic kind");
390 }
391}
392
John Stilesfcf8cb22020-08-06 14:29:22 -0400393// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
394// Cells that don't exist in the source matrix will be populated with identity-matrix values.
395void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
396 SkASSERT(rows <= 4);
397 SkASSERT(columns <= 4);
398
399 const char* columnSeparator = "";
400 for (int c = 0; c < columns; ++c) {
401 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
402 columnSeparator = "), ";
403
404 // Determine how many values to take from the source matrix for this row.
405 int swizzleLength = 0;
406 if (c < sourceMatrix.columns()) {
407 swizzleLength = std::min<>(rows, sourceMatrix.rows());
408 }
409
410 // Emit all the values from the source matrix row.
411 bool firstItem;
412 switch (swizzleLength) {
413 case 0: firstItem = true; break;
414 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
415 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
416 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
417 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
418 default: SkUNREACHABLE;
419 }
420
421 // Emit the placeholder identity-matrix cells.
422 for (int r = swizzleLength; r < rows; ++r) {
423 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
424 firstItem = false;
425 }
426 }
427
428 fExtraFunctions.writeText(")");
429}
430
431// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
432// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
433void MetalCodeGenerator::assembleMatrixFromExpressions(
434 const std::vector<std::unique_ptr<Expression>>& args, int rows, int columns) {
435 size_t argIndex = 0;
436 int argPosition = 0;
437
438 const char* columnSeparator = "";
439 for (int c = 0; c < columns; ++c) {
440 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
441 columnSeparator = "), ";
442
443 const char* rowSeparator = "";
444 for (int r = 0; r < rows; ++r) {
445 fExtraFunctions.writeText(rowSeparator);
446 rowSeparator = ", ";
447
448 if (argIndex < args.size()) {
449 const Type& argType = args[argIndex]->fType;
450 switch (argType.kind()) {
451 case Type::kScalar_Kind: {
452 fExtraFunctions.printf("x%zu", argIndex);
453 break;
454 }
455 case Type::kVector_Kind: {
456 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
457 break;
458 }
459 case Type::kMatrix_Kind: {
460 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
461 argPosition / argType.rows(),
462 argPosition % argType.rows());
463 break;
464 }
465 default: {
466 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
467 fExtraFunctions.writeText("<error>");
468 break;
469 }
470 }
471
472 ++argPosition;
473 if (argPosition >= argType.columns() * argType.rows()) {
474 ++argIndex;
475 argPosition = 0;
476 }
477 } else {
478 SkDEBUGFAIL("not enough arguments for matrix constructor");
479 fExtraFunctions.writeText("<error>");
480 }
481 }
482 }
483
484 if (argPosition != 0 || argIndex != args.size()) {
485 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
486 fExtraFunctions.writeText(", <error>");
487 }
488
489 fExtraFunctions.writeText(")");
490}
491
John Stiles1bdafbf2020-05-28 12:17:20 -0400492// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
493// Keeps track of previously generated constructors so that we won't generate more than one
494// constructor for any given permutation of input argument types. Returns the name of the
495// generated constructor method.
496String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
497 const Type& matrix = c.fType;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500498 int columns = matrix.columns();
499 int rows = matrix.rows();
John Stiles1bdafbf2020-05-28 12:17:20 -0400500 const std::vector<std::unique_ptr<Expression>>& args = c.fArguments;
501
502 // Create the helper-method name and use it as our lookup key.
503 String name;
504 name.appendf("float%dx%d_from", columns, rows);
505 for (const std::unique_ptr<Expression>& expr : args) {
506 name.appendf("_%s", expr->fType.displayName().c_str());
507 }
508
509 // If a helper-method has already been synthesized, we don't need to synthesize it again.
510 auto [iter, newlyCreated] = fHelpers.insert(name);
511 if (!newlyCreated) {
512 return name;
513 }
514
515 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
516 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
517 // supply a mixture of scalars and vectors.)
518 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
519
520 size_t argIndex = 0;
521 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400522 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400523 fExtraFunctions.printf("%s%s x%zu", argSeparator,
524 expr->fType.displayName().c_str(), argIndex++);
525 argSeparator = ", ";
526 }
527
528 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
529
John Stilesfcf8cb22020-08-06 14:29:22 -0400530 if (args.size() == 1 && args.front()->fType.kind() == Type::kMatrix_Kind) {
531 this->assembleMatrixFromMatrix(args.front()->fType, rows, columns);
532 } else {
533 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400534 }
535
John Stilesfcf8cb22020-08-06 14:29:22 -0400536 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500537 return name;
538}
539
540bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
541 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
542 return false;
543 }
544 if (t1.columns() > 1) {
545 return this->canCoerce(t1.componentType(), t2.componentType());
546 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500547 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500548}
549
John Stiles1bdafbf2020-05-28 12:17:20 -0400550bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
551 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
552 if (c.fType.kind() != Type::kMatrix_Kind) {
553 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500554 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400555
556 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
557 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
558 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
559 // scalars can be constructed trivially. In more complex cases, we generate a helper function
560 // that converts our inputs into a properly-shaped matrix.
561 // A matrix construct helper method is always used if any input argument is a matrix.
562 // Helper methods are also necessary when any argument would span multiple rows. For instance:
563 //
564 // float2 x = (1, 2);
565 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
566 // | 2 4 6 |
567 //
568 // float2 x = (2, 3);
569 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
570 // | 2 4 6 |
571 //
572 // float4 x = (1, 2, 3, 4);
573 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
574 // | 2 4 |
575 //
576
577 int position = 0;
578 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
579 // If an input argument is a matrix, we need a helper function.
580 if (expr->fType.kind() == Type::kMatrix_Kind) {
581 return true;
582 }
583 position += expr->fType.columns();
584 if (position > c.fType.rows()) {
585 // An input argument would span multiple rows; a helper function is required.
586 return true;
587 }
588 if (position == c.fType.rows()) {
589 // We've advanced to the end of a row. Wrap to the start of the next row.
590 position = 0;
591 }
592 }
593
594 return false;
595}
596
597void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
598 // Handle special cases for single-argument constructors.
599 if (c.fArguments.size() == 1) {
600 // If the type is coercible, emit it directly.
601 const Expression& arg = *c.fArguments.front();
602 if (this->canCoerce(c.fType, arg.fType)) {
603 this->writeExpression(arg, parentPrecedence);
604 return;
605 }
606
607 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
608 // matrix constructor.
609 if (c.fType.kind() == Type::kMatrix_Kind && arg.fType.isNumber()) {
610 const Type& matrix = c.fType;
611 this->write("float");
612 this->write(to_string(matrix.columns()));
613 this->write("x");
614 this->write(to_string(matrix.rows()));
615 this->write("(");
616 this->writeExpression(arg, parentPrecedence);
617 this->write(")");
618 return;
619 }
620 }
621
622 // Emit and invoke a matrix-constructor helper method if one is necessary.
623 if (this->matrixConstructHelperIsNeeded(c)) {
624 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000625 this->write("(");
626 const char* separator = "";
John Stiles1bdafbf2020-05-28 12:17:20 -0400627 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
John Stiles1fa15b12020-05-28 17:36:54 +0000628 this->write(separator);
629 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400630 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400631 }
John Stiles1fa15b12020-05-28 17:36:54 +0000632 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400633 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400634 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400635
636 // Explicitly invoke the constructor, passing in the necessary arguments.
637 this->writeType(c.fType);
638 this->write("(");
639 const char* separator = "";
640 int scalarCount = 0;
641 for (const std::unique_ptr<Expression>& arg : c.fArguments) {
642 this->write(separator);
643 separator = ", ";
644 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() < c.fType.rows()) {
645 // Merge scalars and smaller vectors together.
646 if (!scalarCount) {
647 this->writeType(c.fType.componentType());
648 this->write(to_string(c.fType.rows()));
649 this->write("(");
650 }
651 scalarCount += arg->fType.columns();
652 }
653 this->writeExpression(*arg, kSequence_Precedence);
654 if (scalarCount && scalarCount == c.fType.rows()) {
655 this->write(")");
656 scalarCount = 0;
657 }
658 }
659 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400660}
661
662void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400663 if (fRTHeightName.length()) {
664 this->write("float4(_fragCoord.x, ");
665 this->write(fRTHeightName.c_str());
666 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500667 } else {
668 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
669 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400670}
671
672void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
673 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
674 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400675 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400676 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400677 case SK_FRAGCOORD_BUILTIN:
678 this->writeFragCoord();
679 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400680 case SK_VERTEXID_BUILTIN:
681 this->write("sk_VertexID");
682 break;
683 case SK_INSTANCEID_BUILTIN:
684 this->write("sk_InstanceID");
685 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400686 case SK_CLOCKWISE_BUILTIN:
687 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400688 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400689 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
690 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400691 default:
692 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
693 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
694 this->write("_in.");
695 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400696 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400697 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
698 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400699 this->write("_uniforms.");
700 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400701 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400702 }
703 }
Timothy Liang651286f2018-06-07 09:55:33 -0400704 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400705 }
706}
707
708void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
709 this->writeExpression(*expr.fBase, kPostfix_Precedence);
710 this->write("[");
711 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
712 this->write("]");
713}
714
715void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400716 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400717 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
718 this->writeExpression(*f.fBase, kPostfix_Precedence);
719 this->write(".");
720 }
Timothy Liang7d637782018-06-05 09:58:07 -0400721 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400722 case SK_CLIPDISTANCE_BUILTIN:
723 this->write("gl_ClipDistance");
724 break;
725 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400726 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400727 break;
728 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400729 if (field->fName == "sk_PointSize") {
730 this->write("_out->sk_PointSize");
731 } else {
732 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
733 this->write("_globals->");
734 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
735 this->write("->");
736 }
Timothy Liang651286f2018-06-07 09:55:33 -0400737 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400738 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400739 }
740}
741
742void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500743 int last = swizzle.fComponents.back();
744 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
745 this->writeType(swizzle.fType);
746 this->write("(");
747 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400748 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
749 this->write(".");
750 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500751 if (c >= 0) {
752 this->write(&("x\0y\0z\0w\0"[c * 2]));
753 }
754 }
755 if (last == SKSL_SWIZZLE_0) {
756 this->write(", 0)");
757 }
758 else if (last == SKSL_SWIZZLE_1) {
759 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400760 }
761}
762
763MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
764 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400765 case Token::Kind::TK_STAR: // fall through
766 case Token::Kind::TK_SLASH: // fall through
767 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
768 case Token::Kind::TK_PLUS: // fall through
769 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
770 case Token::Kind::TK_SHL: // fall through
771 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
772 case Token::Kind::TK_LT: // fall through
773 case Token::Kind::TK_GT: // fall through
774 case Token::Kind::TK_LTEQ: // fall through
775 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
776 case Token::Kind::TK_EQEQ: // fall through
777 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
778 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
779 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
780 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
781 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
782 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
783 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
784 case Token::Kind::TK_EQ: // fall through
785 case Token::Kind::TK_PLUSEQ: // fall through
786 case Token::Kind::TK_MINUSEQ: // fall through
787 case Token::Kind::TK_STAREQ: // fall through
788 case Token::Kind::TK_SLASHEQ: // fall through
789 case Token::Kind::TK_PERCENTEQ: // fall through
790 case Token::Kind::TK_SHLEQ: // fall through
791 case Token::Kind::TK_SHREQ: // fall through
792 case Token::Kind::TK_LOGICALANDEQ: // fall through
793 case Token::Kind::TK_LOGICALXOREQ: // fall through
794 case Token::Kind::TK_LOGICALOREQ: // fall through
795 case Token::Kind::TK_BITWISEANDEQ: // fall through
796 case Token::Kind::TK_BITWISEXOREQ: // fall through
797 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
798 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400799 default: ABORT("unsupported binary operator");
800 }
801}
802
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500803void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
804 const Type& result) {
805 String key = "TimesEqual" + left.name() + right.name();
806 if (fHelpers.find(key) == fHelpers.end()) {
807 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
808 " left = left * right;\n"
809 " return left;\n"
810 "}", result.name().c_str(), left.name().c_str(),
811 right.name().c_str());
812 }
813}
814
Ethan Nicholascc305772017-10-13 16:17:45 -0400815void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
816 Precedence parentPrecedence) {
817 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500818 bool needParens = precedence >= parentPrecedence;
819 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400820 case Token::Kind::TK_EQEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500821 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
822 this->write("all");
823 needParens = true;
824 }
825 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400826 case Token::Kind::TK_NEQ:
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500827 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400828 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500829 needParens = true;
830 }
831 break;
832 default:
833 break;
834 }
835 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400836 this->write("(");
837 }
838 if (Compiler::IsAssignment(b.fOperator) &&
839 Expression::kVariableReference_Kind == b.fLeft->fKind &&
840 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
841 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
842 // writing to an out parameter. Since we have to turn those into pointers, we have to
843 // dereference it here.
844 this->write("*");
845 }
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400846 if (b.fOperator == Token::Kind::TK_STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500847 b.fRight->fType.kind() == Type::kMatrix_Kind) {
848 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
849 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400850 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400851 if (b.fOperator != Token::Kind::TK_EQ && Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholascc305772017-10-13 16:17:45 -0400852 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
853 // This doesn't compile in Metal:
854 // float4 x = float4(1);
855 // x.xy *= float2x2(...);
856 // with the error message "non-const reference cannot bind to vector element",
857 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
858 // as long as the LHS has no side effects, and hope for the best otherwise.
859 this->write(" = ");
860 this->writeExpression(*b.fLeft, kAssignment_Precedence);
861 this->write(" ");
862 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400863 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400864 this->write(op.substr(0, op.size() - 1).c_str());
865 this->write(" ");
866 } else {
867 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
868 }
869 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500870 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400871 this->write(")");
872 }
873}
874
875void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
876 Precedence parentPrecedence) {
877 if (kTernary_Precedence >= parentPrecedence) {
878 this->write("(");
879 }
880 this->writeExpression(*t.fTest, kTernary_Precedence);
881 this->write(" ? ");
882 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
883 this->write(" : ");
884 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
885 if (kTernary_Precedence >= parentPrecedence) {
886 this->write(")");
887 }
888}
889
890void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
891 Precedence parentPrecedence) {
892 if (kPrefix_Precedence >= parentPrecedence) {
893 this->write("(");
894 }
895 this->write(Compiler::OperatorName(p.fOperator));
896 this->writeExpression(*p.fOperand, kPrefix_Precedence);
897 if (kPrefix_Precedence >= parentPrecedence) {
898 this->write(")");
899 }
900}
901
902void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
903 Precedence parentPrecedence) {
904 if (kPostfix_Precedence >= parentPrecedence) {
905 this->write("(");
906 }
907 this->writeExpression(*p.fOperand, kPostfix_Precedence);
908 this->write(Compiler::OperatorName(p.fOperator));
909 if (kPostfix_Precedence >= parentPrecedence) {
910 this->write(")");
911 }
912}
913
914void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
915 this->write(b.fValue ? "true" : "false");
916}
917
918void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
919 if (i.fType == *fContext.fUInt_Type) {
920 this->write(to_string(i.fValue & 0xffffffff) + "u");
921 } else {
922 this->write(to_string((int32_t) i.fValue));
923 }
924}
925
926void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
927 this->write(to_string(f.fValue));
928}
929
930void MetalCodeGenerator::writeSetting(const Setting& s) {
931 ABORT("internal error; setting was not folded to a constant during compilation\n");
932}
933
934void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400935 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400936 const char* separator = "";
937 if ("main" == f.fDeclaration.fName) {
938 switch (fProgram.fKind) {
939 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400940 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400941 break;
942 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400943 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400944 break;
945 default:
John Stilesf7d70432020-05-28 15:46:38 -0400946 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -0400947 }
948 this->write("(Inputs _in [[stage_in]]");
949 if (-1 != fUniformBuffer) {
950 this->write(", constant Uniforms& _uniforms [[buffer(" +
951 to_string(fUniformBuffer) + ")]]");
952 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400953 for (const auto& e : fProgram) {
954 if (ProgramElement::kVar_Kind == e.fKind) {
955 VarDeclarations& decls = (VarDeclarations&) e;
956 if (!decls.fVars.size()) {
957 continue;
958 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400959 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400960 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400961 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
John Stiles08cb2c12020-07-06 10:18:49 -0400962 if (var.fVar->fModifiers.fLayout.fBinding < 0) {
963 fErrors.error(decls.fOffset,
964 "Metal samplers must have 'layout(binding=...)'");
965 }
Timothy Liang7d637782018-06-05 09:58:07 -0400966 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400967 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400968 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400969 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
970 this->write(")]]");
971 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400972 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400973 this->write(SAMPLER_SUFFIX);
974 this->write("[[sampler(");
975 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400976 this->write(")]]");
977 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400978 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400979 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
980 InterfaceBlock& intf = (InterfaceBlock&) e;
981 if ("sk_PerVertex" == intf.fTypeName) {
982 continue;
983 }
984 this->write(", constant ");
985 this->writeType(intf.fVariable.fType);
986 this->write("& " );
987 this->write(fInterfaceBlockNameMap[&intf]);
988 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400989 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400990 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400991 }
992 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500993 if (fProgram.fKind == Program::kFragment_Kind) {
994 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400995 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400996 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400997 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400998 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400999 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001000 } else if (fProgram.fKind == Program::kVertex_Kind) {
1001 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001002 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001003 separator = ", ";
1004 } else {
1005 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -04001006 this->write(" ");
1007 this->writeName(f.fDeclaration.fName);
1008 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001009 Requirements requirements = this->requirements(f.fDeclaration);
1010 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001011 this->write("Inputs _in");
1012 separator = ", ";
1013 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001014 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001015 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001016 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001017 separator = ", ";
1018 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001019 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001020 this->write(separator);
1021 this->write("Uniforms _uniforms");
1022 separator = ", ";
1023 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001024 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001025 this->write(separator);
1026 this->write("thread Globals* _globals");
1027 separator = ", ";
1028 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001029 if (requirements & kFragCoord_Requirement) {
1030 this->write(separator);
1031 this->write("float4 _fragCoord");
1032 separator = ", ";
1033 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001034 }
1035 for (const auto& param : f.fDeclaration.fParameters) {
1036 this->write(separator);
1037 separator = ", ";
1038 this->writeModifiers(param->fModifiers, false);
1039 std::vector<int> sizes;
1040 const Type* type = &param->fType;
1041 while (Type::kArray_Kind == type->kind()) {
1042 sizes.push_back(type->columns());
1043 type = &type->componentType();
1044 }
1045 this->writeType(*type);
1046 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
1047 this->write("*");
1048 }
Timothy Liang651286f2018-06-07 09:55:33 -04001049 this->write(" ");
1050 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001051 for (int s : sizes) {
1052 if (s <= 0) {
1053 this->write("[]");
1054 } else {
1055 this->write("[" + to_string(s) + "]");
1056 }
1057 }
1058 }
1059 this->writeLine(") {");
1060
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001061 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001062
Ethan Nicholascc305772017-10-13 16:17:45 -04001063 if ("main" == f.fDeclaration.fName) {
John Stilescdcdb042020-07-06 09:03:51 -04001064 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001065 this->writeLine(" Outputs _outputStruct;");
1066 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001067 }
John Stilesc67b3622020-05-28 17:53:13 -04001068
Ethan Nicholascc305772017-10-13 16:17:45 -04001069 fFunctionHeader = "";
1070 OutputStream* oldOut = fOut;
1071 StringStream buffer;
1072 fOut = &buffer;
1073 fIndentation++;
1074 this->writeStatements(((Block&) *f.fBody).fStatements);
1075 if ("main" == f.fDeclaration.fName) {
1076 switch (fProgram.fKind) {
1077 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001078 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001079 break;
1080 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001081 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001082 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001083 break;
1084 default:
John Stilesf7d70432020-05-28 15:46:38 -04001085 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001086 }
1087 }
1088 fIndentation--;
1089 this->writeLine("}");
1090
1091 fOut = oldOut;
1092 this->write(fFunctionHeader);
1093 this->write(buffer.str());
1094}
1095
1096void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1097 bool globalContext) {
1098 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1099 this->write("thread ");
1100 }
1101 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001102 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001103 }
1104}
1105
1106void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1107 if ("sk_PerVertex" == intf.fTypeName) {
1108 return;
1109 }
1110 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001111 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001112 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001113 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001114 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -04001115 while (Type::kArray_Kind == structType->kind()) {
1116 structType = &structType->componentType();
1117 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001118 fIndentation++;
1119 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001120 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001121 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001122 }
1123 fIndentation--;
1124 this->write("}");
1125 if (intf.fInstanceName.size()) {
1126 this->write(" ");
1127 this->write(intf.fInstanceName);
1128 for (const auto& size : intf.fSizes) {
1129 this->write("[");
1130 if (size) {
1131 this->writeExpression(*size, kTopLevel_Precedence);
1132 }
1133 this->write("]");
1134 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001135 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1136 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001137 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001138 }
1139 this->writeLine(";");
1140}
1141
Timothy Liangdc89f192018-06-13 09:20:31 -04001142void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1143 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001144 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001145 int currentOffset = 0;
1146 for (const auto& field: fields) {
1147 int fieldOffset = field.fModifiers.fLayout.fOffset;
1148 const Type* fieldType = field.fType;
1149 if (fieldOffset != -1) {
1150 if (currentOffset > fieldOffset) {
1151 fErrors.error(parentOffset,
1152 "offset of field '" + field.fName + "' must be at least " +
1153 to_string((int) currentOffset));
1154 } else if (currentOffset < fieldOffset) {
1155 this->write("char pad");
1156 this->write(to_string(fPaddingCount++));
1157 this->write("[");
1158 this->write(to_string(fieldOffset - currentOffset));
1159 this->writeLine("];");
1160 currentOffset = fieldOffset;
1161 }
1162 int alignment = memoryLayout.alignment(*fieldType);
1163 if (fieldOffset % alignment) {
1164 fErrors.error(parentOffset,
1165 "offset of field '" + field.fName + "' must be a multiple of " +
1166 to_string((int) alignment));
1167 }
1168 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001169 currentOffset += memoryLayout.size(*fieldType);
1170 std::vector<int> sizes;
1171 while (fieldType->kind() == Type::kArray_Kind) {
1172 sizes.push_back(fieldType->columns());
1173 fieldType = &fieldType->componentType();
1174 }
1175 this->writeModifiers(field.fModifiers, false);
1176 this->writeType(*fieldType);
1177 this->write(" ");
1178 this->writeName(field.fName);
1179 for (int s : sizes) {
1180 if (s <= 0) {
1181 this->write("[]");
1182 } else {
1183 this->write("[" + to_string(s) + "]");
1184 }
1185 }
1186 this->writeLine(";");
1187 if (parentIntf) {
1188 fInterfaceBlockMap[&field] = parentIntf;
1189 }
1190 }
1191}
1192
Ethan Nicholascc305772017-10-13 16:17:45 -04001193void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1194 this->writeExpression(value, kTopLevel_Precedence);
1195}
1196
Timothy Liang651286f2018-06-07 09:55:33 -04001197void MetalCodeGenerator::writeName(const String& name) {
1198 if (fReservedWords.find(name) != fReservedWords.end()) {
1199 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1200 }
1201 this->write(name);
1202}
1203
Ethan Nicholascc305772017-10-13 16:17:45 -04001204void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001205 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001206 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001207 for (const auto& stmt : decl.fVars) {
1208 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001209 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001210 continue;
1211 }
1212 if (wroteType) {
1213 this->write(", ");
1214 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001215 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001216 this->writeType(decl.fBaseType);
1217 this->write(" ");
1218 wroteType = true;
1219 }
Timothy Liang651286f2018-06-07 09:55:33 -04001220 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001221 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001222 this->write("[");
1223 if (size) {
1224 this->writeExpression(*size, kTopLevel_Precedence);
1225 }
1226 this->write("]");
1227 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001228 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001229 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001230 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001231 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001232 }
1233 if (wroteType) {
1234 this->write(";");
1235 }
1236}
1237
1238void MetalCodeGenerator::writeStatement(const Statement& s) {
1239 switch (s.fKind) {
1240 case Statement::kBlock_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001241 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001242 break;
1243 case Statement::kExpression_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001244 this->writeExpression(*s.as<ExpressionStatement>().fExpression, kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 this->write(";");
1246 break;
1247 case Statement::kReturn_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001248 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001249 break;
1250 case Statement::kVarDeclarations_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001251 this->writeVarDeclarations(*s.as<VarDeclarationsStatement>().fDeclaration, false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001252 break;
1253 case Statement::kIf_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001254 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001255 break;
1256 case Statement::kFor_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001257 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001258 break;
1259 case Statement::kWhile_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001260 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001261 break;
1262 case Statement::kDo_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001263 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001264 break;
1265 case Statement::kSwitch_Kind:
John Stiles26f98502020-08-18 09:30:51 -04001266 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001267 break;
1268 case Statement::kBreak_Kind:
1269 this->write("break;");
1270 break;
1271 case Statement::kContinue_Kind:
1272 this->write("continue;");
1273 break;
1274 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001275 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001276 break;
1277 case Statement::kNop_Kind:
1278 this->write(";");
1279 break;
1280 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001281#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001282 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001283#endif
1284 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001285 }
1286}
1287
1288void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1289 for (const auto& s : statements) {
1290 if (!s->isEmpty()) {
1291 this->writeStatement(*s);
1292 this->writeLine();
1293 }
1294 }
1295}
1296
1297void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001298 if (b.fIsScope) {
1299 this->writeLine("{");
1300 fIndentation++;
1301 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001302 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001303 if (b.fIsScope) {
1304 fIndentation--;
1305 this->write("}");
1306 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001307}
1308
1309void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1310 this->write("if (");
1311 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1312 this->write(") ");
1313 this->writeStatement(*stmt.fIfTrue);
1314 if (stmt.fIfFalse) {
1315 this->write(" else ");
1316 this->writeStatement(*stmt.fIfFalse);
1317 }
1318}
1319
1320void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1321 this->write("for (");
1322 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1323 this->writeStatement(*f.fInitializer);
1324 } else {
1325 this->write("; ");
1326 }
1327 if (f.fTest) {
1328 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1329 }
1330 this->write("; ");
1331 if (f.fNext) {
1332 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1333 }
1334 this->write(") ");
1335 this->writeStatement(*f.fStatement);
1336}
1337
1338void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1339 this->write("while (");
1340 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1341 this->write(") ");
1342 this->writeStatement(*w.fStatement);
1343}
1344
1345void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1346 this->write("do ");
1347 this->writeStatement(*d.fStatement);
1348 this->write(" while (");
1349 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1350 this->write(");");
1351}
1352
1353void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1354 this->write("switch (");
1355 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1356 this->writeLine(") {");
1357 fIndentation++;
1358 for (const auto& c : s.fCases) {
1359 if (c->fValue) {
1360 this->write("case ");
1361 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1362 this->writeLine(":");
1363 } else {
1364 this->writeLine("default:");
1365 }
1366 fIndentation++;
1367 for (const auto& stmt : c->fStatements) {
1368 this->writeStatement(*stmt);
1369 this->writeLine();
1370 }
1371 fIndentation--;
1372 }
1373 fIndentation--;
1374 this->write("}");
1375}
1376
1377void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1378 this->write("return");
1379 if (r.fExpression) {
1380 this->write(" ");
1381 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1382 }
1383 this->write(";");
1384}
1385
1386void MetalCodeGenerator::writeHeader() {
1387 this->write("#include <metal_stdlib>\n");
1388 this->write("#include <simd/simd.h>\n");
1389 this->write("using namespace metal;\n");
1390}
1391
1392void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001393 for (const auto& e : fProgram) {
1394 if (ProgramElement::kVar_Kind == e.fKind) {
1395 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001396 if (!decls.fVars.size()) {
1397 continue;
1398 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001399 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001400 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1401 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001402 if (-1 == fUniformBuffer) {
1403 this->write("struct Uniforms {\n");
1404 fUniformBuffer = first.fModifiers.fLayout.fSet;
1405 if (-1 == fUniformBuffer) {
1406 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1407 }
1408 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1409 if (-1 == fUniformBuffer) {
1410 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1411 "the same 'layout(set=...)'");
1412 }
1413 }
1414 this->write(" ");
1415 this->writeType(first.fType);
1416 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001417 for (const auto& stmt : decls.fVars) {
1418 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001419 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001420 }
1421 this->write(";\n");
1422 }
1423 }
1424 }
1425 if (-1 != fUniformBuffer) {
1426 this->write("};\n");
1427 }
1428}
1429
1430void MetalCodeGenerator::writeInputStruct() {
1431 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001432 for (const auto& e : fProgram) {
1433 if (ProgramElement::kVar_Kind == e.fKind) {
1434 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001435 if (!decls.fVars.size()) {
1436 continue;
1437 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001438 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1440 -1 == first.fModifiers.fLayout.fBuiltin) {
1441 this->write(" ");
1442 this->writeType(first.fType);
1443 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001444 for (const auto& stmt : decls.fVars) {
1445 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001446 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001447 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001448 if (fProgram.fKind == Program::kVertex_Kind) {
1449 this->write(" [[attribute(" +
1450 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1451 } else if (fProgram.fKind == Program::kFragment_Kind) {
1452 this->write(" [[user(locn" +
1453 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1454 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001455 }
1456 }
1457 this->write(";\n");
1458 }
1459 }
1460 }
1461 this->write("};\n");
1462}
1463
1464void MetalCodeGenerator::writeOutputStruct() {
1465 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001466 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001467 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001468 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001469 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001470 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001471 for (const auto& e : fProgram) {
1472 if (ProgramElement::kVar_Kind == e.fKind) {
1473 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001474 if (!decls.fVars.size()) {
1475 continue;
1476 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001477 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001478 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1479 -1 == first.fModifiers.fLayout.fBuiltin) {
1480 this->write(" ");
1481 this->writeType(first.fType);
1482 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001483 for (const auto& stmt : decls.fVars) {
1484 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001485 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001486 if (fProgram.fKind == Program::kVertex_Kind) {
1487 this->write(" [[user(locn" +
1488 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1489 } else if (fProgram.fKind == Program::kFragment_Kind) {
1490 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001491 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1492 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1493 if (colorIndex) {
1494 this->write(", index(" + to_string(colorIndex) + ")");
1495 }
1496 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001497 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001498 }
1499 this->write(";\n");
1500 }
1501 }
Timothy Liang7d637782018-06-05 09:58:07 -04001502 }
1503 if (fProgram.fKind == Program::kVertex_Kind) {
1504 this->write(" float sk_PointSize;\n");
1505 }
1506 this->write("};\n");
1507}
1508
1509void MetalCodeGenerator::writeInterfaceBlocks() {
1510 bool wroteInterfaceBlock = false;
1511 for (const auto& e : fProgram) {
1512 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1513 this->writeInterfaceBlock((InterfaceBlock&) e);
1514 wroteInterfaceBlock = true;
1515 }
1516 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001517 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001518 this->writeLine("struct sksl_synthetic_uniforms {");
1519 this->writeLine(" float u_skRTHeight;");
1520 this->writeLine("};");
1521 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001522}
1523
John Stilescdcdb042020-07-06 09:03:51 -04001524void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1525 // Visit the interface blocks.
1526 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1527 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1528 }
1529 for (const ProgramElement& element : fProgram) {
1530 if (element.fKind != ProgramElement::kVar_Kind) {
1531 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001532 }
John Stilescdcdb042020-07-06 09:03:51 -04001533 const VarDeclarations& decls = static_cast<const VarDeclarations&>(element);
1534 if (decls.fVars.empty()) {
1535 continue;
1536 }
1537 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
1538 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1539 first.fType.kind() == Type::kSampler_Kind) {
1540 for (const auto& stmt : decls.fVars) {
1541 VarDeclaration& var = static_cast<VarDeclaration&>(*stmt);
John Stilesc67b3622020-05-28 17:53:13 -04001542
John Stilescdcdb042020-07-06 09:03:51 -04001543 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1544 // Samplers are represented as a "texture/sampler" duo in the global struct.
1545 visitor->VisitTexture(first.fType, var.fVar->fName);
1546 visitor->VisitSampler(first.fType, String(var.fVar->fName) + SAMPLER_SUFFIX);
1547 } else {
1548 // Visit a regular variable.
1549 visitor->VisitVariable(*var.fVar, var.fValue.get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001550 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001551 }
1552 }
1553 }
John Stilescdcdb042020-07-06 09:03:51 -04001554}
1555
1556void MetalCodeGenerator::writeGlobalStruct() {
1557 class : public GlobalStructVisitor {
1558 public:
1559 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1560 this->AddElement();
1561 fCodeGen->write(" constant ");
1562 fCodeGen->write(block.fTypeName);
1563 fCodeGen->write("* ");
1564 fCodeGen->writeName(blockName);
1565 fCodeGen->write(";\n");
1566 }
1567 void VisitTexture(const Type& type, const String& name) override {
1568 this->AddElement();
1569 fCodeGen->write(" ");
1570 fCodeGen->writeType(type);
1571 fCodeGen->write(" ");
1572 fCodeGen->writeName(name);
1573 fCodeGen->write(";\n");
1574 }
1575 void VisitSampler(const Type&, const String& name) override {
1576 this->AddElement();
1577 fCodeGen->write(" sampler ");
1578 fCodeGen->writeName(name);
1579 fCodeGen->write(";\n");
1580 }
1581 void VisitVariable(const Variable& var, const Expression* value) override {
1582 this->AddElement();
1583 fCodeGen->write(" ");
1584 fCodeGen->writeType(var.fType);
1585 fCodeGen->write(" ");
1586 fCodeGen->writeName(var.fName);
1587 fCodeGen->write(";\n");
1588 }
1589 void AddElement() {
1590 if (fFirst) {
1591 fCodeGen->write("struct Globals {\n");
1592 fFirst = false;
1593 }
1594 }
1595 void Finish() {
1596 if (!fFirst) {
1597 fCodeGen->write("};");
1598 fFirst = true;
1599 }
1600 }
1601
1602 MetalCodeGenerator* fCodeGen = nullptr;
1603 bool fFirst = true;
1604 } visitor;
1605
1606 visitor.fCodeGen = this;
1607 this->visitGlobalStruct(&visitor);
1608 visitor.Finish();
1609}
1610
1611void MetalCodeGenerator::writeGlobalInit() {
1612 class : public GlobalStructVisitor {
1613 public:
1614 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1615 const String& blockName) override {
1616 this->AddElement();
1617 fCodeGen->write("&");
1618 fCodeGen->writeName(blockName);
1619 }
1620 void VisitTexture(const Type&, const String& name) override {
1621 this->AddElement();
1622 fCodeGen->writeName(name);
1623 }
1624 void VisitSampler(const Type&, const String& name) override {
1625 this->AddElement();
1626 fCodeGen->writeName(name);
1627 }
1628 void VisitVariable(const Variable& var, const Expression* value) override {
1629 this->AddElement();
1630 if (value) {
1631 fCodeGen->writeVarInitializer(var, *value);
1632 } else {
1633 fCodeGen->write("{}");
1634 }
1635 }
1636 void AddElement() {
1637 if (fFirst) {
1638 fCodeGen->write(" Globals globalStruct{");
1639 fFirst = false;
1640 } else {
1641 fCodeGen->write(", ");
1642 }
1643 }
1644 void Finish() {
1645 if (!fFirst) {
1646 fCodeGen->writeLine("};");
1647 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1648 fCodeGen->writeLine(" (void)_globals;");
1649 }
1650 }
1651 MetalCodeGenerator* fCodeGen = nullptr;
1652 bool fFirst = true;
1653 } visitor;
1654
1655 visitor.fCodeGen = this;
1656 this->visitGlobalStruct(&visitor);
1657 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001658}
1659
Ethan Nicholascc305772017-10-13 16:17:45 -04001660void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1661 switch (e.fKind) {
1662 case ProgramElement::kExtension_Kind:
1663 break;
1664 case ProgramElement::kVar_Kind: {
1665 VarDeclarations& decl = (VarDeclarations&) e;
1666 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001667 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001668 if (-1 == builtin) {
1669 // normal var
1670 this->writeVarDeclarations(decl, true);
1671 this->writeLine();
1672 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1673 // ignore
1674 }
1675 }
1676 break;
1677 }
1678 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001679 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001680 break;
1681 case ProgramElement::kFunction_Kind:
1682 this->writeFunction((FunctionDefinition&) e);
1683 break;
1684 case ProgramElement::kModifiers_Kind:
1685 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1686 this->writeLine(";");
1687 break;
1688 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001689#ifdef SK_DEBUG
1690 ABORT("unsupported program element: %s\n", e.description().c_str());
1691#endif
1692 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001693 }
1694}
1695
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001696MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1697 if (!e) {
1698 return kNo_Requirements;
1699 }
1700 switch (e->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001701 case Expression::kFunctionCall_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001702 const FunctionCall& f = (const FunctionCall&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001703 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001704 for (const auto& arg : f.fArguments) {
1705 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001706 }
1707 return result;
1708 }
1709 case Expression::kConstructor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001710 const Constructor& c = (const Constructor&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001711 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001712 for (const auto& arg : c.fArguments) {
1713 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001714 }
1715 return result;
1716 }
Timothy Liang7d637782018-06-05 09:58:07 -04001717 case Expression::kFieldAccess_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001718 const FieldAccess& f = (const FieldAccess&) *e;
Timothy Liang7d637782018-06-05 09:58:07 -04001719 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1720 return kGlobals_Requirement;
1721 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001722 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001723 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001724 case Expression::kSwizzle_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001725 return this->requirements(((const Swizzle&) *e).fBase.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001726 case Expression::kBinary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001727 const BinaryExpression& b = (const BinaryExpression&) *e;
1728 return this->requirements(b.fLeft.get()) | this->requirements(b.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001729 }
1730 case Expression::kIndex_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001731 const IndexExpression& idx = (const IndexExpression&) *e;
1732 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001733 }
1734 case Expression::kPrefix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001735 return this->requirements(((const PrefixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001736 case Expression::kPostfix_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001737 return this->requirements(((const PostfixExpression&) *e).fOperand.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001738 case Expression::kTernary_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001739 const TernaryExpression& t = (const TernaryExpression&) *e;
1740 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1741 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001742 }
1743 case Expression::kVariableReference_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001744 const VariableReference& v = (const VariableReference&) *e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001745 Requirements result = kNo_Requirements;
1746 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001747 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001748 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1749 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1750 result = kInputs_Requirement;
1751 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1752 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001753 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1754 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001755 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001756 } else {
1757 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001758 }
1759 }
1760 return result;
1761 }
1762 default:
1763 return kNo_Requirements;
1764 }
1765}
1766
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001767MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1768 if (!s) {
1769 return kNo_Requirements;
1770 }
1771 switch (s->fKind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001772 case Statement::kBlock_Kind: {
1773 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001774 for (const auto& child : ((const Block*) s)->fStatements) {
1775 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001776 }
1777 return result;
1778 }
Timothy Liang7d637782018-06-05 09:58:07 -04001779 case Statement::kVarDeclaration_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001780 const VarDeclaration& var = (const VarDeclaration&) *s;
1781 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001782 }
1783 case Statement::kVarDeclarations_Kind: {
1784 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001785 const VarDeclarations& decls = *((const VarDeclarationsStatement&) *s).fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001786 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001787 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001788 }
1789 return result;
1790 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001791 case Statement::kExpression_Kind:
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001792 return this->requirements(((const ExpressionStatement&) *s).fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001793 case Statement::kReturn_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001794 const ReturnStatement& r = (const ReturnStatement&) *s;
1795 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001796 }
1797 case Statement::kIf_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001798 const IfStatement& i = (const IfStatement&) *s;
1799 return this->requirements(i.fTest.get()) |
1800 this->requirements(i.fIfTrue.get()) |
1801 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001802 }
1803 case Statement::kFor_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001804 const ForStatement& f = (const ForStatement&) *s;
1805 return this->requirements(f.fInitializer.get()) |
1806 this->requirements(f.fTest.get()) |
1807 this->requirements(f.fNext.get()) |
1808 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001809 }
1810 case Statement::kWhile_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001811 const WhileStatement& w = (const WhileStatement&) *s;
1812 return this->requirements(w.fTest.get()) |
1813 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001814 }
1815 case Statement::kDo_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001816 const DoStatement& d = (const DoStatement&) *s;
1817 return this->requirements(d.fTest.get()) |
1818 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001819 }
1820 case Statement::kSwitch_Kind: {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001821 const SwitchStatement& sw = (const SwitchStatement&) *s;
1822 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001823 for (const auto& c : sw.fCases) {
1824 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001825 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001826 }
1827 }
1828 return result;
1829 }
1830 default:
1831 return kNo_Requirements;
1832 }
1833}
1834
1835MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1836 if (f.fBuiltin) {
1837 return kNo_Requirements;
1838 }
1839 auto found = fRequirements.find(&f);
1840 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001841 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001842 for (const auto& e : fProgram) {
1843 if (ProgramElement::kFunction_Kind == e.fKind) {
1844 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001845 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001846 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001847 fRequirements[&f] = reqs;
1848 return reqs;
1849 }
1850 }
1851 }
1852 }
1853 return found->second;
1854}
1855
Timothy Liangb8eeb802018-07-23 16:46:16 -04001856bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001857 OutputStream* rawOut = fOut;
1858 fOut = &fHeader;
1859 fProgramKind = fProgram.fKind;
1860 this->writeHeader();
1861 this->writeUniformStruct();
1862 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001863 this->writeOutputStruct();
1864 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001865 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001866 StringStream body;
1867 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001868 for (const auto& e : fProgram) {
1869 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001870 }
1871 fOut = rawOut;
1872
1873 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001874 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001875 write_stringstream(body, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001876 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001877}
1878
John Stilesa6841be2020-08-06 14:11:56 -04001879} // namespace SkSL