blob: c7f6abd8e751c6396236a84035964ce40762435d [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"
John Stiles0023c0c2020-11-16 13:32:18 -050011#include "src/sksl/SkSLMemoryLayout.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/sksl/ir/SkSLExpressionStatement.h"
13#include "src/sksl/ir/SkSLExtension.h"
14#include "src/sksl/ir/SkSLIndexExpression.h"
15#include "src/sksl/ir/SkSLModifiersDeclaration.h"
16#include "src/sksl/ir/SkSLNop.h"
17#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040018
Brian Osmanc262a122020-08-06 16:34:34 -040019#include <algorithm>
20
Ethan Nicholascc305772017-10-13 16:17:45 -040021namespace SkSL {
22
John Stilescdcdb042020-07-06 09:03:51 -040023class MetalCodeGenerator::GlobalStructVisitor {
24public:
25 virtual ~GlobalStructVisitor() = default;
26 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
27 virtual void VisitTexture(const Type& type, const String& name) = 0;
28 virtual void VisitSampler(const Type& type, const String& name) = 0;
29 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
30};
31
Timothy Liangee84fe12018-05-18 14:38:19 -040032void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040033#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
34#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040035 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040036 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050037 fIntrinsicMap[String("equal")] = METAL(Equal);
38 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040039 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
40 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
41 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
42 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040043}
44
Ethan Nicholascc305772017-10-13 16:17:45 -040045void MetalCodeGenerator::write(const char* s) {
46 if (!s[0]) {
47 return;
48 }
49 if (fAtLineStart) {
50 for (int i = 0; i < fIndentation; i++) {
51 fOut->writeText(" ");
52 }
53 }
54 fOut->writeText(s);
55 fAtLineStart = false;
56}
57
58void MetalCodeGenerator::writeLine(const char* s) {
59 this->write(s);
60 fOut->writeText(fLineEnding);
61 fAtLineStart = true;
62}
63
64void MetalCodeGenerator::write(const String& s) {
65 this->write(s.c_str());
66}
67
68void MetalCodeGenerator::writeLine(const String& s) {
69 this->writeLine(s.c_str());
70}
71
72void MetalCodeGenerator::writeLine() {
73 this->writeLine("");
74}
75
76void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040077 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040078}
79
Ethan Nicholas45fa8102020-01-13 10:58:49 -050080String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040081 switch (type.typeKind()) {
82 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050083 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040084 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050085 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
86 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050088 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040089 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040090 if (type == *fContext.fHalf_Type) {
91 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050092 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040093 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050094 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040095 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050096 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040097 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050098 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040099 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400100 }
101}
102
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500103void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400104 if (type.typeKind() == Type::TypeKind::kStruct) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500105 for (const Type* search : fWrittenStructs) {
106 if (*search == type) {
107 // already written
108 this->write(type.name());
109 return;
110 }
111 }
112 fWrittenStructs.push_back(&type);
113 this->writeLine("struct " + type.name() + " {");
114 fIndentation++;
115 this->writeFields(type.fields(), type.fOffset);
116 fIndentation--;
117 this->write("}");
118 } else {
119 this->write(this->typeName(type));
120 }
121}
122
Ethan Nicholascc305772017-10-13 16:17:45 -0400123void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400124 switch (expr.kind()) {
125 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400126 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400127 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400128 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400129 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400130 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400131 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400132 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400133 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400134 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400135 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400136 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400137 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400138 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400139 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400140 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400141 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400142 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400143 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400144 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400145 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400146 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400147 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400148 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400149 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400150 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400151 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400152 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400153 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400154 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400155 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400156 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400159 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400162 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400163 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400165 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 break;
167 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500168#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500170#endif
171 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 }
173}
174
Timothy Liang6403b0e2018-05-17 10:40:04 -0400175void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400176 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400177 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400178 Intrinsic intrinsic = i->second;
179 int32_t intrinsicId = intrinsic.second;
180 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400181 case kSpecial_IntrinsicKind:
182 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400183 break;
184 case kMetal_IntrinsicKind:
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400185 this->writeExpression(*c.arguments()[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400186 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500187 case kEqual_MetalIntrinsic:
188 this->write(" == ");
189 break;
190 case kNotEqual_MetalIntrinsic:
191 this->write(" != ");
192 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400193 case kLessThan_MetalIntrinsic:
194 this->write(" < ");
195 break;
196 case kLessThanEqual_MetalIntrinsic:
197 this->write(" <= ");
198 break;
199 case kGreaterThan_MetalIntrinsic:
200 this->write(" > ");
201 break;
202 case kGreaterThanEqual_MetalIntrinsic:
203 this->write(" >= ");
204 break;
205 default:
206 ABORT("unsupported metal intrinsic kind");
207 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400208 this->writeExpression(*c.arguments()[1], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400209 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400210 default:
211 ABORT("unsupported intrinsic kind");
212 }
213}
214
Ethan Nicholascc305772017-10-13 16:17:45 -0400215void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400216 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400217 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400218 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400219 if (entry != fIntrinsicMap.end()) {
220 this->writeIntrinsicCall(c);
221 return;
222 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400223 const StringFragment& name = function.name();
Ethan Nicholased84b732020-10-08 11:45:44 -0400224 bool builtin = function.isBuiltin();
225 if (builtin && name == "atan" && arguments.size() == 2) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400226 this->write("atan2");
Ethan Nicholased84b732020-10-08 11:45:44 -0400227 } else if (builtin && name == "inversesqrt") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400228 this->write("rsqrt");
Ethan Nicholased84b732020-10-08 11:45:44 -0400229 } else if (builtin && name == "inverse") {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400230 SkASSERT(arguments.size() == 1);
231 this->writeInverseHack(*arguments[0]);
John Stilesa80a3dc2020-10-20 10:24:56 -0400232 } else if (builtin && name == "frexp") {
233 // Our Metal codegen assumes that out params are pointers, but Metal's built-in frexp
234 // actually takes a reference for the exponent, not a pointer. We add in a helper function
235 // here to translate.
236 SkASSERT(arguments.size() == 2);
237 auto [iter, newlyCreated] = fHelpers.insert("frexp");
238 if (newlyCreated) {
239 fExtraFunctions.printf(
240 "float frexp(float arg, thread int* exp) { return frexp(arg, *exp); }\n");
241 }
242 this->write("frexp");
Ethan Nicholased84b732020-10-08 11:45:44 -0400243 } else if (builtin && name == "dFdx") {
Timothy Liang7d637782018-06-05 09:58:07 -0400244 this->write("dfdx");
Ethan Nicholased84b732020-10-08 11:45:44 -0400245 } else if (builtin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700246 // Flipping Y also negates the Y derivatives.
247 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400248 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400249 this->writeName(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400250 }
251 this->write("(");
252 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400253 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400254 this->write("_in");
255 separator = ", ";
256 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400257 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400258 this->write(separator);
259 this->write("_out");
260 separator = ", ";
261 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400262 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400263 this->write(separator);
264 this->write("_uniforms");
265 separator = ", ";
266 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400267 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400268 this->write(separator);
269 this->write("_globals");
270 separator = ", ";
271 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400272 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400273 this->write(separator);
274 this->write("_fragCoord");
275 separator = ", ";
276 }
Brian Osman5bf3e202020-10-13 10:34:18 -0400277 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400278 for (size_t i = 0; i < arguments.size(); ++i) {
279 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400280 this->write(separator);
281 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400282 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400283 this->write("&");
284 }
285 this->writeExpression(arg, kSequence_Precedence);
286 }
287 this->write(")");
288}
289
Chris Daltondba7aab2018-11-15 10:57:49 -0500290void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400291 const Type& type = mat.type();
292 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500293 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400294 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500295 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
296 fWrittenIntrinsics.insert(name);
297 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500298 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500299 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
300 "}"
301 ).c_str());
302 }
303 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400304 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500305 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
306 fWrittenIntrinsics.insert(name);
307 fExtraFunctions.writeText((
308 typeName + " " + name + "(" + typeName + " m) {"
309 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
310 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
311 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
312 " float b01 = a22 * a11 - a12 * a21;"
313 " float b11 = -a22 * a10 + a12 * a20;"
314 " float b21 = a21 * a10 - a11 * a20;"
315 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
316 " return " + typeName +
317 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
318 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
319 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
320 " (1/det);"
321 "}"
322 ).c_str());
323 }
324 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400325 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500326 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
327 fWrittenIntrinsics.insert(name);
328 fExtraFunctions.writeText((
329 typeName + " " + name + "(" + typeName + " m) {"
330 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
331 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
332 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
333 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
334 " float b00 = a00 * a11 - a01 * a10;"
335 " float b01 = a00 * a12 - a02 * a10;"
336 " float b02 = a00 * a13 - a03 * a10;"
337 " float b03 = a01 * a12 - a02 * a11;"
338 " float b04 = a01 * a13 - a03 * a11;"
339 " float b05 = a02 * a13 - a03 * a12;"
340 " float b06 = a20 * a31 - a21 * a30;"
341 " float b07 = a20 * a32 - a22 * a30;"
342 " float b08 = a20 * a33 - a23 * a30;"
343 " float b09 = a21 * a32 - a22 * a31;"
344 " float b10 = a21 * a33 - a23 * a31;"
345 " float b11 = a22 * a33 - a23 * a32;"
346 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
347 " b04 * b07 + b05 * b06;"
348 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
349 " a02 * b10 - a01 * b11 - a03 * b09,"
350 " a31 * b05 - a32 * b04 + a33 * b03,"
351 " a22 * b04 - a21 * b05 - a23 * b03,"
352 " a12 * b08 - a10 * b11 - a13 * b07,"
353 " a00 * b11 - a02 * b08 + a03 * b07,"
354 " a32 * b02 - a30 * b05 - a33 * b01,"
355 " a20 * b05 - a22 * b02 + a23 * b01,"
356 " a10 * b10 - a11 * b08 + a13 * b06,"
357 " a01 * b08 - a00 * b10 - a03 * b06,"
358 " a30 * b04 - a31 * b02 + a33 * b00,"
359 " a21 * b02 - a20 * b04 - a23 * b00,"
360 " a11 * b07 - a10 * b09 - a12 * b06,"
361 " a00 * b09 - a01 * b07 + a02 * b06,"
362 " a31 * b01 - a30 * b03 - a32 * b00,"
363 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
364 "}"
365 ).c_str());
366 }
367 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500368 this->write(name);
369}
370
Timothy Liang6403b0e2018-05-17 10:40:04 -0400371void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400372 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400373 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400374 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400375 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400376 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400377 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400378 this->write(SAMPLER_SUFFIX);
379 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400380 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400381 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500382 // have to store the vector in a temp variable to avoid double evaluating it
383 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400384 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500385 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400386 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500387 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400388 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400389 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400390 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400391 this->write(")");
392 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400393 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400394 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500395 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400396 // 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 -0500397 String tmpX = "tmpX" + to_string(fVarCount++);
398 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400399 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400400 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500401 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400402 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500403 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400404 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500405 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400406 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500407 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400408 default:
409 ABORT("unsupported special intrinsic kind");
410 }
411}
412
John Stilesfcf8cb22020-08-06 14:29:22 -0400413// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
414// Cells that don't exist in the source matrix will be populated with identity-matrix values.
415void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
416 SkASSERT(rows <= 4);
417 SkASSERT(columns <= 4);
418
419 const char* columnSeparator = "";
420 for (int c = 0; c < columns; ++c) {
421 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
422 columnSeparator = "), ";
423
424 // Determine how many values to take from the source matrix for this row.
425 int swizzleLength = 0;
426 if (c < sourceMatrix.columns()) {
427 swizzleLength = std::min<>(rows, sourceMatrix.rows());
428 }
429
430 // Emit all the values from the source matrix row.
431 bool firstItem;
432 switch (swizzleLength) {
433 case 0: firstItem = true; break;
434 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
435 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
436 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
437 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
438 default: SkUNREACHABLE;
439 }
440
441 // Emit the placeholder identity-matrix cells.
442 for (int r = swizzleLength; r < rows; ++r) {
443 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
444 firstItem = false;
445 }
446 }
447
448 fExtraFunctions.writeText(")");
449}
450
451// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
452// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400453void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
454 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400455 size_t argIndex = 0;
456 int argPosition = 0;
457
458 const char* columnSeparator = "";
459 for (int c = 0; c < columns; ++c) {
460 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
461 columnSeparator = "), ";
462
463 const char* rowSeparator = "";
464 for (int r = 0; r < rows; ++r) {
465 fExtraFunctions.writeText(rowSeparator);
466 rowSeparator = ", ";
467
468 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400469 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400470 switch (argType.typeKind()) {
471 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400472 fExtraFunctions.printf("x%zu", argIndex);
473 break;
474 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400475 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400476 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
477 break;
478 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400479 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400480 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
481 argPosition / argType.rows(),
482 argPosition % argType.rows());
483 break;
484 }
485 default: {
486 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
487 fExtraFunctions.writeText("<error>");
488 break;
489 }
490 }
491
492 ++argPosition;
493 if (argPosition >= argType.columns() * argType.rows()) {
494 ++argIndex;
495 argPosition = 0;
496 }
497 } else {
498 SkDEBUGFAIL("not enough arguments for matrix constructor");
499 fExtraFunctions.writeText("<error>");
500 }
501 }
502 }
503
504 if (argPosition != 0 || argIndex != args.size()) {
505 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
506 fExtraFunctions.writeText(", <error>");
507 }
508
509 fExtraFunctions.writeText(")");
510}
511
John Stiles1bdafbf2020-05-28 12:17:20 -0400512// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
513// Keeps track of previously generated constructors so that we won't generate more than one
514// constructor for any given permutation of input argument types. Returns the name of the
515// generated constructor method.
516String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400517 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500518 int columns = matrix.columns();
519 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400520 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400521
522 // Create the helper-method name and use it as our lookup key.
523 String name;
524 name.appendf("float%dx%d_from", columns, rows);
525 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400526 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400527 }
528
529 // If a helper-method has already been synthesized, we don't need to synthesize it again.
530 auto [iter, newlyCreated] = fHelpers.insert(name);
531 if (!newlyCreated) {
532 return name;
533 }
534
535 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
536 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
537 // supply a mixture of scalars and vectors.)
538 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
539
540 size_t argIndex = 0;
541 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400542 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400543 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400544 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400545 argSeparator = ", ";
546 }
547
548 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
549
Ethan Nicholas30d30222020-09-11 12:27:26 -0400550 if (args.size() == 1 && args.front()->type().typeKind() == Type::TypeKind::kMatrix) {
551 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400552 } else {
553 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400554 }
555
John Stilesfcf8cb22020-08-06 14:29:22 -0400556 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500557 return name;
558}
559
560bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
561 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
562 return false;
563 }
564 if (t1.columns() > 1) {
565 return this->canCoerce(t1.componentType(), t2.componentType());
566 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500567 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500568}
569
John Stiles1bdafbf2020-05-28 12:17:20 -0400570bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
571 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400572 if (c.type().typeKind() != Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400573 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500574 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400575
576 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
577 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
578 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
579 // scalars can be constructed trivially. In more complex cases, we generate a helper function
580 // that converts our inputs into a properly-shaped matrix.
581 // A matrix construct helper method is always used if any input argument is a matrix.
582 // Helper methods are also necessary when any argument would span multiple rows. For instance:
583 //
584 // float2 x = (1, 2);
585 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
586 // | 2 4 6 |
587 //
588 // float2 x = (2, 3);
589 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
590 // | 2 4 6 |
591 //
592 // float4 x = (1, 2, 3, 4);
593 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
594 // | 2 4 |
595 //
596
597 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400598 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400599 // If an input argument is a matrix, we need a helper function.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400600 if (expr->type().typeKind() == Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400601 return true;
602 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400603 position += expr->type().columns();
604 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400605 // An input argument would span multiple rows; a helper function is required.
606 return true;
607 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400608 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400609 // We've advanced to the end of a row. Wrap to the start of the next row.
610 position = 0;
611 }
612 }
613
614 return false;
615}
616
617void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400618 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400619 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400620 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400621 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400622 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400623 const Type& argType = arg.type();
624 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400625 this->writeExpression(arg, parentPrecedence);
626 return;
627 }
628
629 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
630 // matrix constructor.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400631 if (constructorType.typeKind() == Type::TypeKind::kMatrix && argType.isNumber()) {
632 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400633 this->write("float");
634 this->write(to_string(matrix.columns()));
635 this->write("x");
636 this->write(to_string(matrix.rows()));
637 this->write("(");
638 this->writeExpression(arg, parentPrecedence);
639 this->write(")");
640 return;
641 }
642 }
643
644 // Emit and invoke a matrix-constructor helper method if one is necessary.
645 if (this->matrixConstructHelperIsNeeded(c)) {
646 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000647 this->write("(");
648 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400649 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000650 this->write(separator);
651 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400652 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400653 }
John Stiles1fa15b12020-05-28 17:36:54 +0000654 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400655 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400656 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400657
658 // Explicitly invoke the constructor, passing in the necessary arguments.
Ethan Nicholas30d30222020-09-11 12:27:26 -0400659 this->writeType(constructorType);
John Stiles1bdafbf2020-05-28 12:17:20 -0400660 this->write("(");
661 const char* separator = "";
662 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400663 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400664 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400665 this->write(separator);
666 separator = ", ";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400667 if (constructorType.typeKind() == Type::TypeKind::kMatrix &&
668 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400669 // Merge scalars and smaller vectors together.
670 if (!scalarCount) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400671 this->writeType(constructorType.componentType());
672 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400673 this->write("(");
674 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400675 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400676 }
677 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400678 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400679 this->write(")");
680 scalarCount = 0;
681 }
682 }
683 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400684}
685
686void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400687 if (fRTHeightName.length()) {
688 this->write("float4(_fragCoord.x, ");
689 this->write(fRTHeightName.c_str());
690 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500691 } else {
692 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
693 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400694}
695
696void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400697 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400698 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400699 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400700 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400701 case SK_FRAGCOORD_BUILTIN:
702 this->writeFragCoord();
703 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400704 case SK_VERTEXID_BUILTIN:
705 this->write("sk_VertexID");
706 break;
707 case SK_INSTANCEID_BUILTIN:
708 this->write("sk_InstanceID");
709 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400710 case SK_CLOCKWISE_BUILTIN:
711 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400712 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400713 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
714 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400715 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400716 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400717 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400718 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400719 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400720 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400721 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400722 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
723 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400724 this->write("_uniforms.");
725 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400726 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400727 }
728 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400729 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400730 }
731}
732
733void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400734 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400735 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400736 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400737 this->write("]");
738}
739
740void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400741 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
742 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
743 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400744 this->write(".");
745 }
Timothy Liang7d637782018-06-05 09:58:07 -0400746 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400747 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400748 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400749 break;
750 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400751 if (field->fName == "sk_PointSize") {
752 this->write("_out->sk_PointSize");
753 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400754 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400755 this->write("_globals->");
756 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
757 this->write("->");
758 }
Timothy Liang651286f2018-06-07 09:55:33 -0400759 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400760 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400761 }
762}
763
764void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400765 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400766 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400767 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -0400768 SkASSERT(c >= 0 && c <= 3);
769 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400770 }
771}
772
773MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
774 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400775 case Token::Kind::TK_STAR: // fall through
776 case Token::Kind::TK_SLASH: // fall through
777 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
778 case Token::Kind::TK_PLUS: // fall through
779 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
780 case Token::Kind::TK_SHL: // fall through
781 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
782 case Token::Kind::TK_LT: // fall through
783 case Token::Kind::TK_GT: // fall through
784 case Token::Kind::TK_LTEQ: // fall through
785 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
786 case Token::Kind::TK_EQEQ: // fall through
787 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
788 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
789 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
790 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
791 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
792 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
793 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
794 case Token::Kind::TK_EQ: // fall through
795 case Token::Kind::TK_PLUSEQ: // fall through
796 case Token::Kind::TK_MINUSEQ: // fall through
797 case Token::Kind::TK_STAREQ: // fall through
798 case Token::Kind::TK_SLASHEQ: // fall through
799 case Token::Kind::TK_PERCENTEQ: // fall through
800 case Token::Kind::TK_SHLEQ: // fall through
801 case Token::Kind::TK_SHREQ: // fall through
802 case Token::Kind::TK_LOGICALANDEQ: // fall through
803 case Token::Kind::TK_LOGICALXOREQ: // fall through
804 case Token::Kind::TK_LOGICALOREQ: // fall through
805 case Token::Kind::TK_BITWISEANDEQ: // fall through
806 case Token::Kind::TK_BITWISEXOREQ: // fall through
807 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
808 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400809 default: ABORT("unsupported binary operator");
810 }
811}
812
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500813void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
814 const Type& result) {
815 String key = "TimesEqual" + left.name() + right.name();
816 if (fHelpers.find(key) == fHelpers.end()) {
817 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
818 " left = left * right;\n"
819 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400820 "}", String(result.name()).c_str(), String(left.name()).c_str(),
821 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500822 }
823}
824
Ethan Nicholascc305772017-10-13 16:17:45 -0400825void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
826 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -0400827 const Expression& left = *b.left();
828 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400829 const Type& leftType = left.type();
830 const Type& rightType = right.type();
831 Token::Kind op = b.getOperator();
832 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500833 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400834 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400835 case Token::Kind::TK_EQEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400836 if (leftType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500837 this->write("all");
838 needParens = true;
839 }
840 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400841 case Token::Kind::TK_NEQ:
Ethan Nicholas30d30222020-09-11 12:27:26 -0400842 if (leftType.typeKind() == Type::TypeKind::kVector) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400843 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500844 needParens = true;
845 }
846 break;
847 default:
848 break;
849 }
850 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400851 this->write("(");
852 }
Brian Osman79457ef2020-09-24 15:01:27 -0400853 if (Compiler::IsAssignment(op) && left.is<VariableReference>() &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400854 left.as<VariableReference>().variable()->storage() == Variable::Storage::kParameter &&
Ethan Nicholas78686922020-10-08 06:46:27 -0400855 left.as<VariableReference>().variable()->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400856 // writing to an out parameter. Since we have to turn those into pointers, we have to
857 // dereference it here.
858 this->write("*");
859 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400860 if (op == Token::Kind::TK_STAREQ && leftType.typeKind() == Type::TypeKind::kMatrix &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400861 rightType.typeKind() == Type::TypeKind::kMatrix) {
862 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500863 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400864 this->writeExpression(left, precedence);
865 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
866 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400867 // This doesn't compile in Metal:
868 // float4 x = float4(1);
869 // x.xy *= float2x2(...);
870 // with the error message "non-const reference cannot bind to vector element",
871 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
872 // as long as the LHS has no side effects, and hope for the best otherwise.
873 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400874 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400875 this->write(" ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400876 String opName = Compiler::OperatorName(op);
877 SkASSERT(opName.endsWith("="));
878 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400879 this->write(" ");
880 } else {
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400881 this->write(String(" ") + Compiler::OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400882 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400883 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500884 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400885 this->write(")");
886 }
887}
888
889void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
890 Precedence parentPrecedence) {
891 if (kTernary_Precedence >= parentPrecedence) {
892 this->write("(");
893 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400894 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400895 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400896 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400897 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400898 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400899 if (kTernary_Precedence >= parentPrecedence) {
900 this->write(")");
901 }
902}
903
904void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
905 Precedence parentPrecedence) {
906 if (kPrefix_Precedence >= parentPrecedence) {
907 this->write("(");
908 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400909 this->write(Compiler::OperatorName(p.getOperator()));
910 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400911 if (kPrefix_Precedence >= parentPrecedence) {
912 this->write(")");
913 }
914}
915
916void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
917 Precedence parentPrecedence) {
918 if (kPostfix_Precedence >= parentPrecedence) {
919 this->write("(");
920 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -0400921 this->writeExpression(*p.operand(), kPostfix_Precedence);
922 this->write(Compiler::OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400923 if (kPostfix_Precedence >= parentPrecedence) {
924 this->write(")");
925 }
926}
927
928void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -0400929 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -0400930}
931
932void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400933 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400934 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -0400935 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -0400936 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400937 }
938}
939
940void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -0400941 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -0400942}
943
944void MetalCodeGenerator::writeSetting(const Setting& s) {
945 ABORT("internal error; setting was not folded to a constant during compilation\n");
946}
947
John Stiles569249b2020-11-03 12:18:22 -0500948bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400949 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400950 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -0500951 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400952 switch (fProgram.fKind) {
953 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400954 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400955 break;
956 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400957 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400958 break;
959 default:
John Stiles3fabfc02020-09-25 15:51:28 -0400960 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -0500961 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -0400962 }
963 this->write("(Inputs _in [[stage_in]]");
964 if (-1 != fUniformBuffer) {
965 this->write(", constant Uniforms& _uniforms [[buffer(" +
966 to_string(fUniformBuffer) + ")]]");
967 }
Brian Osman1179fcf2020-10-08 16:04:40 -0400968 for (const auto& e : fProgram.elements()) {
969 if (e->is<GlobalVarDeclaration>()) {
970 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400971 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
972 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
973 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -0400974 fErrors.error(decls.fOffset,
975 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -0500976 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -0400977 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400978 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -0500979 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -0400980 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -0500981 return false;
Brian Osmanc0213602020-10-06 14:43:32 -0400982 }
983 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400984 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -0400985 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400986 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -0400987 this->write(")]]");
988 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400989 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -0400990 this->write(SAMPLER_SUFFIX);
991 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -0400992 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -0400993 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400994 }
Brian Osman1179fcf2020-10-08 16:04:40 -0400995 } else if (e->is<InterfaceBlock>()) {
996 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -0400997 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400998 continue;
999 }
1000 this->write(", constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001001 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001002 this->write("& " );
1003 this->write(fInterfaceBlockNameMap[&intf]);
1004 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001005 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001006 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001007 }
1008 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001009 if (fProgram.fKind == Program::kFragment_Kind) {
1010 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001011 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001012 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001013 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001014 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001015 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001016 } else if (fProgram.fKind == Program::kVertex_Kind) {
1017 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001018 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001019 separator = ", ";
1020 } else {
John Stiles569249b2020-11-03 12:18:22 -05001021 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001022 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001023 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001024 this->write("(");
John Stiles569249b2020-11-03 12:18:22 -05001025 Requirements requirements = this->requirements(f);
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001026 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001027 this->write("Inputs _in");
1028 separator = ", ";
1029 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001030 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001031 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001032 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001033 separator = ", ";
1034 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001035 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001036 this->write(separator);
1037 this->write("Uniforms _uniforms");
1038 separator = ", ";
1039 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001040 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001041 this->write(separator);
1042 this->write("thread Globals* _globals");
1043 separator = ", ";
1044 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001045 if (requirements & kFragCoord_Requirement) {
1046 this->write(separator);
1047 this->write("float4 _fragCoord");
1048 separator = ", ";
1049 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001050 }
John Stiles569249b2020-11-03 12:18:22 -05001051 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001052 this->write(separator);
1053 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001054 this->writeModifiers(param->modifiers(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001055 std::vector<int> sizes;
Ethan Nicholas30d30222020-09-11 12:27:26 -04001056 const Type* type = &param->type();
Ethan Nicholase6592142020-09-08 10:22:09 -04001057 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001058 sizes.push_back(type->columns());
1059 type = &type->componentType();
1060 }
1061 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001062 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001063 this->write("*");
1064 }
Timothy Liang651286f2018-06-07 09:55:33 -04001065 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001066 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001067 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001068 if (s == Type::kUnsizedArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001069 this->write("[]");
1070 } else {
1071 this->write("[" + to_string(s) + "]");
1072 }
1073 }
1074 }
John Stiles569249b2020-11-03 12:18:22 -05001075 this->write(")");
1076 return true;
1077}
Ethan Nicholascc305772017-10-13 16:17:45 -04001078
John Stiles569249b2020-11-03 12:18:22 -05001079void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1080 this->writeFunctionDeclaration(f.declaration());
1081 this->writeLine(";");
1082}
1083
1084void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001085 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001086
John Stiles569249b2020-11-03 12:18:22 -05001087 if (!this->writeFunctionDeclaration(f.declaration())) {
1088 return;
1089 }
1090
1091 this->writeLine(" {");
1092
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001093 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001094 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001095 this->writeLine(" Outputs _outputStruct;");
1096 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001097 }
John Stilesc67b3622020-05-28 17:53:13 -04001098
Ethan Nicholascc305772017-10-13 16:17:45 -04001099 fFunctionHeader = "";
1100 OutputStream* oldOut = fOut;
1101 StringStream buffer;
1102 fOut = &buffer;
1103 fIndentation++;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001104 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001105 if (!stmt->isEmpty()) {
1106 this->writeStatement(*stmt);
1107 this->writeLine();
1108 }
1109 }
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001110 if (f.declaration().name() == "main") {
Ethan Nicholascc305772017-10-13 16:17:45 -04001111 switch (fProgram.fKind) {
1112 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001113 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001114 break;
1115 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001116 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001117 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001118 break;
1119 default:
John Stilesf7d70432020-05-28 15:46:38 -04001120 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001121 }
1122 }
1123 fIndentation--;
1124 this->writeLine("}");
1125
1126 fOut = oldOut;
1127 this->write(fFunctionHeader);
1128 this->write(buffer.str());
1129}
1130
1131void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1132 bool globalContext) {
1133 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1134 this->write("thread ");
1135 }
1136 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001137 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001138 }
1139}
1140
1141void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001142 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001143 return;
1144 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001145 this->writeModifiers(intf.variable().modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001146 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001147 this->writeLine(intf.typeName() + " {");
1148 const Type* structType = &intf.variable().type();
Timothy Lianga06f2152018-05-24 15:33:31 -04001149 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001150 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001151 structType = &structType->componentType();
1152 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001153 fIndentation++;
1154 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001155 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001156 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001157 }
1158 fIndentation--;
1159 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001160 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001161 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001162 this->write(intf.instanceName());
1163 for (const auto& size : intf.sizes()) {
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 Nicholaseaf47882020-10-15 10:10:08 -04001170 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001171 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001172 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001173 }
1174 this->writeLine(";");
1175}
1176
Timothy Liangdc89f192018-06-13 09:20:31 -04001177void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1178 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001179 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001180 int currentOffset = 0;
1181 for (const auto& field: fields) {
1182 int fieldOffset = field.fModifiers.fLayout.fOffset;
1183 const Type* fieldType = field.fType;
John Stiles0023c0c2020-11-16 13:32:18 -05001184 if (!memoryLayout.layoutIsSupported(*fieldType)) {
1185 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1186 return;
1187 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001188 if (fieldOffset != -1) {
1189 if (currentOffset > fieldOffset) {
1190 fErrors.error(parentOffset,
1191 "offset of field '" + field.fName + "' must be at least " +
1192 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001193 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001194 } else if (currentOffset < fieldOffset) {
1195 this->write("char pad");
1196 this->write(to_string(fPaddingCount++));
1197 this->write("[");
1198 this->write(to_string(fieldOffset - currentOffset));
1199 this->writeLine("];");
1200 currentOffset = fieldOffset;
1201 }
1202 int alignment = memoryLayout.alignment(*fieldType);
1203 if (fieldOffset % alignment) {
1204 fErrors.error(parentOffset,
1205 "offset of field '" + field.fName + "' must be a multiple of " +
1206 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001207 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001208 }
1209 }
Brian Osman8609a242020-09-08 14:01:49 -04001210 size_t fieldSize = memoryLayout.size(*fieldType);
1211 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1212 fErrors.error(parentOffset, "field offset overflow");
1213 return;
1214 }
1215 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001216 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001217 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001218 sizes.push_back(fieldType->columns());
1219 fieldType = &fieldType->componentType();
1220 }
1221 this->writeModifiers(field.fModifiers, false);
1222 this->writeType(*fieldType);
1223 this->write(" ");
1224 this->writeName(field.fName);
1225 for (int s : sizes) {
Brian Osmane8c26082020-10-01 17:22:45 -04001226 if (s == Type::kUnsizedArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001227 this->write("[]");
1228 } else {
1229 this->write("[" + to_string(s) + "]");
1230 }
1231 }
1232 this->writeLine(";");
1233 if (parentIntf) {
1234 fInterfaceBlockMap[&field] = parentIntf;
1235 }
1236 }
1237}
1238
Ethan Nicholascc305772017-10-13 16:17:45 -04001239void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1240 this->writeExpression(value, kTopLevel_Precedence);
1241}
1242
Timothy Liang651286f2018-06-07 09:55:33 -04001243void MetalCodeGenerator::writeName(const String& name) {
1244 if (fReservedWords.find(name) != fReservedWords.end()) {
1245 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1246 }
1247 this->write(name);
1248}
1249
Brian Osmanc0213602020-10-06 14:43:32 -04001250void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001251 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001252 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001253 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001254 this->writeModifiers(var.var().modifiers(), global);
1255 this->writeType(var.baseType());
Brian Osmanc0213602020-10-06 14:43:32 -04001256 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001257 this->writeName(var.var().name());
John Stiles2d4f9592020-10-30 10:29:12 -04001258 for (const std::unique_ptr<Expression>& size : var.sizes()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001259 this->write("[");
John Stiles2d4f9592020-10-30 10:29:12 -04001260 if (size) {
1261 this->writeExpression(*size, kTopLevel_Precedence);
Brian Osmanc0213602020-10-06 14:43:32 -04001262 }
1263 this->write("]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001264 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001265 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001266 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001267 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001268 }
1269 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001270}
1271
1272void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001273 switch (s.kind()) {
1274 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001275 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001276 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001277 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001278 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001279 this->write(";");
1280 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001281 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001282 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001283 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001284 case Statement::Kind::kVarDeclaration:
1285 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001286 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001287 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001288 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001289 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001290 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001291 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001292 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001293 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001294 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001295 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001296 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001297 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001298 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001299 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001300 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001301 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001302 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001303 this->write("break;");
1304 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001305 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001306 this->write("continue;");
1307 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001308 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001309 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001310 break;
John Stiles98c1f822020-09-09 14:18:53 -04001311 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001312 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001313 this->write(";");
1314 break;
1315 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001316#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001317 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001318#endif
1319 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001320 }
1321}
1322
Ethan Nicholascc305772017-10-13 16:17:45 -04001323void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001324 bool isScope = b.isScope();
1325 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001326 this->writeLine("{");
1327 fIndentation++;
1328 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001329 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1330 if (!stmt->isEmpty()) {
1331 this->writeStatement(*stmt);
1332 this->writeLine();
1333 }
1334 }
1335 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001336 fIndentation--;
1337 this->write("}");
1338 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001339}
1340
1341void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1342 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001343 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001344 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001345 this->writeStatement(*stmt.ifTrue());
1346 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001347 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001348 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001349 }
1350}
1351
1352void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1353 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001354 if (f.initializer() && !f.initializer()->isEmpty()) {
1355 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001356 } else {
1357 this->write("; ");
1358 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001359 if (f.test()) {
1360 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001361 }
1362 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001363 if (f.next()) {
1364 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001365 }
1366 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001367 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001368}
1369
1370void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1371 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001372 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001373 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001374 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001375}
1376
1377void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1378 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001379 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001380 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001381 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001382 this->write(");");
1383}
1384
1385void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1386 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001387 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001388 this->writeLine(") {");
1389 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001390 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1391 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001392 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001393 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001394 this->writeLine(":");
1395 } else {
1396 this->writeLine("default:");
1397 }
1398 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001399 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001400 this->writeStatement(*stmt);
1401 this->writeLine();
1402 }
1403 fIndentation--;
1404 }
1405 fIndentation--;
1406 this->write("}");
1407}
1408
1409void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1410 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001411 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001412 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001413 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001414 }
1415 this->write(";");
1416}
1417
1418void MetalCodeGenerator::writeHeader() {
1419 this->write("#include <metal_stdlib>\n");
1420 this->write("#include <simd/simd.h>\n");
1421 this->write("using namespace metal;\n");
1422}
1423
1424void MetalCodeGenerator::writeUniformStruct() {
Brian Osman1179fcf2020-10-08 16:04:40 -04001425 for (const auto& e : fProgram.elements()) {
1426 if (e->is<GlobalVarDeclaration>()) {
1427 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001428 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001429 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001430 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001431 if (-1 == fUniformBuffer) {
1432 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001433 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001434 if (-1 == fUniformBuffer) {
1435 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1436 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001437 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001438 if (-1 == fUniformBuffer) {
1439 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1440 "the same 'layout(set=...)'");
1441 }
1442 }
1443 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001444 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001445 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001446 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001447 this->write(";\n");
1448 }
1449 }
1450 }
1451 if (-1 != fUniformBuffer) {
1452 this->write("};\n");
1453 }
1454}
1455
1456void MetalCodeGenerator::writeInputStruct() {
1457 this->write("struct Inputs {\n");
Brian Osman1179fcf2020-10-08 16:04:40 -04001458 for (const auto& e : fProgram.elements()) {
1459 if (e->is<GlobalVarDeclaration>()) {
1460 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001461 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001462 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1463 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001464 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001465 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001466 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001467 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001468 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001469 if (fProgram.fKind == Program::kVertex_Kind) {
1470 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001471 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001472 } else if (fProgram.fKind == Program::kFragment_Kind) {
1473 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001474 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001475 }
1476 }
1477 this->write(";\n");
1478 }
1479 }
1480 }
1481 this->write("};\n");
1482}
1483
1484void MetalCodeGenerator::writeOutputStruct() {
1485 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001486 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001487 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001488 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001489 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001490 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001491 for (const auto& e : fProgram.elements()) {
1492 if (e->is<GlobalVarDeclaration>()) {
1493 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001494 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001495 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1496 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001497 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001498 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001499 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001500 this->writeName(var.name());
1501 if (fProgram.fKind == Program::kVertex_Kind) {
1502 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001503 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001504 } else if (fProgram.fKind == Program::kFragment_Kind) {
1505 this->write(" [[color(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001506 to_string(var.modifiers().fLayout.fLocation) +")");
1507 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001508 if (colorIndex) {
1509 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001510 }
Brian Osmanc0213602020-10-06 14:43:32 -04001511 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001512 }
1513 this->write(";\n");
1514 }
1515 }
Timothy Liang7d637782018-06-05 09:58:07 -04001516 }
1517 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001518 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001519 }
1520 this->write("};\n");
1521}
1522
1523void MetalCodeGenerator::writeInterfaceBlocks() {
1524 bool wroteInterfaceBlock = false;
Brian Osman1179fcf2020-10-08 16:04:40 -04001525 for (const auto& e : fProgram.elements()) {
1526 if (e->is<InterfaceBlock>()) {
1527 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001528 wroteInterfaceBlock = true;
1529 }
1530 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001531 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001532 this->writeLine("struct sksl_synthetic_uniforms {");
1533 this->writeLine(" float u_skRTHeight;");
1534 this->writeLine("};");
1535 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001536}
1537
John Stilescdcdb042020-07-06 09:03:51 -04001538void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1539 // Visit the interface blocks.
1540 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1541 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1542 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001543 for (const auto& element : fProgram.elements()) {
1544 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001545 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001546 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001547 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1548 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1549 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001550 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001551 var.type().typeKind() == Type::TypeKind::kSampler) {
1552 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1553 // Samplers are represented as a "texture/sampler" duo in the global struct.
1554 visitor->VisitTexture(var.type(), var.name());
1555 visitor->VisitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
1556 } else {
1557 // Visit a regular variable.
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001558 visitor->VisitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001559 }
1560 }
1561 }
John Stilescdcdb042020-07-06 09:03:51 -04001562}
1563
1564void MetalCodeGenerator::writeGlobalStruct() {
1565 class : public GlobalStructVisitor {
1566 public:
1567 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1568 this->AddElement();
1569 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001570 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001571 fCodeGen->write("* ");
1572 fCodeGen->writeName(blockName);
1573 fCodeGen->write(";\n");
1574 }
1575 void VisitTexture(const Type& type, const String& name) override {
1576 this->AddElement();
1577 fCodeGen->write(" ");
1578 fCodeGen->writeType(type);
1579 fCodeGen->write(" ");
1580 fCodeGen->writeName(name);
1581 fCodeGen->write(";\n");
1582 }
1583 void VisitSampler(const Type&, const String& name) override {
1584 this->AddElement();
1585 fCodeGen->write(" sampler ");
1586 fCodeGen->writeName(name);
1587 fCodeGen->write(";\n");
1588 }
1589 void VisitVariable(const Variable& var, const Expression* value) override {
1590 this->AddElement();
1591 fCodeGen->write(" ");
Ethan Nicholas30d30222020-09-11 12:27:26 -04001592 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001593 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001594 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04001595 fCodeGen->write(";\n");
1596 }
1597 void AddElement() {
1598 if (fFirst) {
1599 fCodeGen->write("struct Globals {\n");
1600 fFirst = false;
1601 }
1602 }
1603 void Finish() {
1604 if (!fFirst) {
1605 fCodeGen->write("};");
1606 fFirst = true;
1607 }
1608 }
1609
1610 MetalCodeGenerator* fCodeGen = nullptr;
1611 bool fFirst = true;
1612 } visitor;
1613
1614 visitor.fCodeGen = this;
1615 this->visitGlobalStruct(&visitor);
1616 visitor.Finish();
1617}
1618
1619void MetalCodeGenerator::writeGlobalInit() {
1620 class : public GlobalStructVisitor {
1621 public:
1622 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1623 const String& blockName) override {
1624 this->AddElement();
1625 fCodeGen->write("&");
1626 fCodeGen->writeName(blockName);
1627 }
1628 void VisitTexture(const Type&, const String& name) override {
1629 this->AddElement();
1630 fCodeGen->writeName(name);
1631 }
1632 void VisitSampler(const Type&, const String& name) override {
1633 this->AddElement();
1634 fCodeGen->writeName(name);
1635 }
1636 void VisitVariable(const Variable& var, const Expression* value) override {
1637 this->AddElement();
1638 if (value) {
1639 fCodeGen->writeVarInitializer(var, *value);
1640 } else {
1641 fCodeGen->write("{}");
1642 }
1643 }
1644 void AddElement() {
1645 if (fFirst) {
1646 fCodeGen->write(" Globals globalStruct{");
1647 fFirst = false;
1648 } else {
1649 fCodeGen->write(", ");
1650 }
1651 }
1652 void Finish() {
1653 if (!fFirst) {
1654 fCodeGen->writeLine("};");
1655 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1656 fCodeGen->writeLine(" (void)_globals;");
1657 }
1658 }
1659 MetalCodeGenerator* fCodeGen = nullptr;
1660 bool fFirst = true;
1661 } visitor;
1662
1663 visitor.fCodeGen = this;
1664 this->visitGlobalStruct(&visitor);
1665 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001666}
1667
Ethan Nicholascc305772017-10-13 16:17:45 -04001668void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001669 switch (e.kind()) {
1670 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001671 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001672 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001673 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1674 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1675 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001676 if (-1 == builtin) {
1677 // normal var
1678 this->writeVarDeclaration(decl, true);
1679 this->writeLine();
1680 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1681 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001682 }
1683 break;
1684 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001685 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001686 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001687 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001688 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001689 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001690 break;
John Stiles569249b2020-11-03 12:18:22 -05001691 case ProgramElement::Kind::kFunctionPrototype:
1692 this->writeFunctionPrototype(e.as<FunctionPrototype>());
1693 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001694 case ProgramElement::Kind::kModifiers:
Ethan Nicholas077050b2020-10-13 10:30:20 -04001695 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(), true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001696 this->writeLine(";");
1697 break;
1698 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001699#ifdef SK_DEBUG
1700 ABORT("unsupported program element: %s\n", e.description().c_str());
1701#endif
1702 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001703 }
1704}
1705
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001706MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1707 if (!e) {
1708 return kNo_Requirements;
1709 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001710 switch (e->kind()) {
1711 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001712 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001713 Requirements result = this->requirements(f.function());
1714 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001715 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001716 }
1717 return result;
1718 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001719 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001720 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001721 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001722 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001723 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001724 }
1725 return result;
1726 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001727 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001728 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001729 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001730 return kGlobals_Requirement;
1731 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001732 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001733 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001734 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001735 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001736 case Expression::Kind::kBinary: {
1737 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001738 return this->requirements(bin.left().get()) |
1739 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001740 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001741 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001742 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001743 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001744 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001745 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001746 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001747 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001748 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001749 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001750 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001751 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1752 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001753 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001754 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001755 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001756 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001757 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001758 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001759 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001760 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001761 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001762 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001763 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001764 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001765 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001766 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001767 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001768 } else {
1769 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001770 }
1771 }
1772 return result;
1773 }
1774 default:
1775 return kNo_Requirements;
1776 }
1777}
1778
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001779MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1780 if (!s) {
1781 return kNo_Requirements;
1782 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001783 switch (s->kind()) {
1784 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001786 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001787 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001788 }
1789 return result;
1790 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001791 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001792 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001793 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001794 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001795 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001796 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001797 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001798 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001799 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001800 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001801 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001802 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001803 return this->requirements(i.test().get()) |
1804 this->requirements(i.ifTrue().get()) |
1805 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001806 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001807 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001808 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001809 return this->requirements(f.initializer().get()) |
1810 this->requirements(f.test().get()) |
1811 this->requirements(f.next().get()) |
1812 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001814 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001815 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001816 return this->requirements(w.test().get()) |
1817 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001818 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001819 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001820 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001821 return this->requirements(d.test().get()) |
1822 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001823 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001824 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001825 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001826 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04001827 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
1828 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001829 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001830 }
1831 }
1832 return result;
1833 }
1834 default:
1835 return kNo_Requirements;
1836 }
1837}
1838
1839MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001840 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001841 return kNo_Requirements;
1842 }
1843 auto found = fRequirements.find(&f);
1844 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001845 fRequirements[&f] = kNo_Requirements;
Brian Osman1179fcf2020-10-08 16:04:40 -04001846 for (const auto& e : fProgram.elements()) {
1847 if (e->is<FunctionDefinition>()) {
1848 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001849 if (&def.declaration() == &f) {
1850 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001851 fRequirements[&f] = reqs;
1852 return reqs;
1853 }
1854 }
1855 }
John Stiles569249b2020-11-03 12:18:22 -05001856 // We never found a definition for this declared function, but it's legal to prototype a
1857 // function without ever giving a definition, as long as you don't call it.
1858 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04001859 }
1860 return found->second;
1861}
1862
Timothy Liangb8eeb802018-07-23 16:46:16 -04001863bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 OutputStream* rawOut = fOut;
1865 fOut = &fHeader;
1866 fProgramKind = fProgram.fKind;
1867 this->writeHeader();
1868 this->writeUniformStruct();
1869 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001870 this->writeOutputStruct();
1871 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001872 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001873 StringStream body;
1874 fOut = &body;
Brian Osman1179fcf2020-10-08 16:04:40 -04001875 for (const auto& e : fProgram.elements()) {
1876 this->writeProgramElement(*e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001877 }
1878 fOut = rawOut;
1879
1880 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001881 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001882 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04001883 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04001884}
1885
John Stilesa6841be2020-08-06 14:11:56 -04001886} // namespace SkSL