blob: bafa4d598485bf7d50dd7518d5cb5bdb43bdda15 [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLCompiler.h"
11#include "src/sksl/ir/SkSLExpressionStatement.h"
12#include "src/sksl/ir/SkSLExtension.h"
13#include "src/sksl/ir/SkSLIndexExpression.h"
14#include "src/sksl/ir/SkSLModifiersDeclaration.h"
15#include "src/sksl/ir/SkSLNop.h"
16#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040017
Brian Osmanc262a122020-08-06 16:34:34 -040018#include <algorithm>
19
Ethan Nicholascc305772017-10-13 16:17:45 -040020namespace SkSL {
21
John Stilescdcdb042020-07-06 09:03:51 -040022class MetalCodeGenerator::GlobalStructVisitor {
23public:
24 virtual ~GlobalStructVisitor() = default;
25 virtual void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
26 virtual void VisitTexture(const Type& type, const String& name) = 0;
27 virtual void VisitSampler(const Type& type, const String& name) = 0;
28 virtual void VisitVariable(const Variable& var, const Expression* value) = 0;
29};
30
Timothy Liangee84fe12018-05-18 14:38:19 -040031void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040032#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
33#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040034 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040035 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050036 fIntrinsicMap[String("equal")] = METAL(Equal);
37 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040038 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
39 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
40 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
41 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040042}
43
Ethan Nicholascc305772017-10-13 16:17:45 -040044void MetalCodeGenerator::write(const char* s) {
45 if (!s[0]) {
46 return;
47 }
48 if (fAtLineStart) {
49 for (int i = 0; i < fIndentation; i++) {
50 fOut->writeText(" ");
51 }
52 }
53 fOut->writeText(s);
54 fAtLineStart = false;
55}
56
57void MetalCodeGenerator::writeLine(const char* s) {
58 this->write(s);
59 fOut->writeText(fLineEnding);
60 fAtLineStart = true;
61}
62
63void MetalCodeGenerator::write(const String& s) {
64 this->write(s.c_str());
65}
66
67void MetalCodeGenerator::writeLine(const String& s) {
68 this->writeLine(s.c_str());
69}
70
71void MetalCodeGenerator::writeLine() {
72 this->writeLine("");
73}
74
75void MetalCodeGenerator::writeExtension(const Extension& ext) {
76 this->writeLine("#extension " + ext.fName + " : enable");
77}
78
Ethan Nicholas45fa8102020-01-13 10:58:49 -050079String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040080 switch (type.typeKind()) {
81 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050082 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040083 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
85 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050087 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040088 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040089 if (type == *fContext.fHalf_Type) {
90 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -050091 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040092 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050093 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040094 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050095 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040096 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -050097 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040098 }
Ethan Nicholascc305772017-10-13 16:17:45 -040099 }
100}
101
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500102void MetalCodeGenerator::writeType(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400103 if (type.typeKind() == Type::TypeKind::kStruct) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500104 for (const Type* search : fWrittenStructs) {
105 if (*search == type) {
106 // already written
107 this->write(type.name());
108 return;
109 }
110 }
111 fWrittenStructs.push_back(&type);
112 this->writeLine("struct " + type.name() + " {");
113 fIndentation++;
114 this->writeFields(type.fields(), type.fOffset);
115 fIndentation--;
116 this->write("}");
117 } else {
118 this->write(this->typeName(type));
119 }
120}
121
Ethan Nicholascc305772017-10-13 16:17:45 -0400122void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (expr.kind()) {
124 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400125 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400127 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400128 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400129 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400130 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400131 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400132 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400133 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400134 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400135 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400136 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400137 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400138 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400139 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400140 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400141 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400142 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400143 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400144 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400145 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400146 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400147 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400148 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400149 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400150 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400151 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400152 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400153 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400154 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400155 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400156 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400157 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400158 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400159 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400160 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400161 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400162 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400163 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400164 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400165 break;
166 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500167#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400168 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500169#endif
170 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400171 }
172}
173
Timothy Liang6403b0e2018-05-17 10:40:04 -0400174void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400175 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400176 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400177 Intrinsic intrinsic = i->second;
178 int32_t intrinsicId = intrinsic.second;
179 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400180 case kSpecial_IntrinsicKind:
181 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400182 break;
183 case kMetal_IntrinsicKind:
184 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
185 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500186 case kEqual_MetalIntrinsic:
187 this->write(" == ");
188 break;
189 case kNotEqual_MetalIntrinsic:
190 this->write(" != ");
191 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400192 case kLessThan_MetalIntrinsic:
193 this->write(" < ");
194 break;
195 case kLessThanEqual_MetalIntrinsic:
196 this->write(" <= ");
197 break;
198 case kGreaterThan_MetalIntrinsic:
199 this->write(" > ");
200 break;
201 case kGreaterThanEqual_MetalIntrinsic:
202 this->write(" >= ");
203 break;
204 default:
205 ABORT("unsupported metal intrinsic kind");
206 }
207 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
208 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400209 default:
210 ABORT("unsupported intrinsic kind");
211 }
212}
213
Ethan Nicholascc305772017-10-13 16:17:45 -0400214void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400215 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
216 if (entry != fIntrinsicMap.end()) {
217 this->writeIntrinsicCall(c);
218 return;
219 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400220 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
221 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400222 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
223 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500224 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
225 SkASSERT(c.fArguments.size() == 1);
226 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400227 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
228 this->write("dfdx");
229 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700230 // Flipping Y also negates the Y derivatives.
231 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400232 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400233 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400234 }
235 this->write("(");
236 const char* separator = "";
237 if (this->requirements(c.fFunction) & kInputs_Requirement) {
238 this->write("_in");
239 separator = ", ";
240 }
241 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
242 this->write(separator);
243 this->write("_out");
244 separator = ", ";
245 }
246 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
247 this->write(separator);
248 this->write("_uniforms");
249 separator = ", ";
250 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400251 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
252 this->write(separator);
253 this->write("_globals");
254 separator = ", ";
255 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400256 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
257 this->write(separator);
258 this->write("_fragCoord");
259 separator = ", ";
260 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400261 for (size_t i = 0; i < c.fArguments.size(); ++i) {
262 const Expression& arg = *c.fArguments[i];
263 this->write(separator);
264 separator = ", ";
265 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
266 this->write("&");
267 }
268 this->writeExpression(arg, kSequence_Precedence);
269 }
270 this->write(")");
271}
272
Chris Daltondba7aab2018-11-15 10:57:49 -0500273void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500274 String typeName = mat.fType.name();
275 String name = typeName + "_inverse";
276 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500277 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
278 fWrittenIntrinsics.insert(name);
279 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500280 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500281 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
282 "}"
283 ).c_str());
284 }
285 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500286 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
287 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
288 fWrittenIntrinsics.insert(name);
289 fExtraFunctions.writeText((
290 typeName + " " + name + "(" + typeName + " m) {"
291 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
292 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
293 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
294 " float b01 = a22 * a11 - a12 * a21;"
295 " float b11 = -a22 * a10 + a12 * a20;"
296 " float b21 = a21 * a10 - a11 * a20;"
297 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
298 " return " + typeName +
299 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
300 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
301 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
302 " (1/det);"
303 "}"
304 ).c_str());
305 }
306 }
307 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
308 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
309 fWrittenIntrinsics.insert(name);
310 fExtraFunctions.writeText((
311 typeName + " " + name + "(" + typeName + " m) {"
312 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
313 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
314 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
315 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
316 " float b00 = a00 * a11 - a01 * a10;"
317 " float b01 = a00 * a12 - a02 * a10;"
318 " float b02 = a00 * a13 - a03 * a10;"
319 " float b03 = a01 * a12 - a02 * a11;"
320 " float b04 = a01 * a13 - a03 * a11;"
321 " float b05 = a02 * a13 - a03 * a12;"
322 " float b06 = a20 * a31 - a21 * a30;"
323 " float b07 = a20 * a32 - a22 * a30;"
324 " float b08 = a20 * a33 - a23 * a30;"
325 " float b09 = a21 * a32 - a22 * a31;"
326 " float b10 = a21 * a33 - a23 * a31;"
327 " float b11 = a22 * a33 - a23 * a32;"
328 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
329 " b04 * b07 + b05 * b06;"
330 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
331 " a02 * b10 - a01 * b11 - a03 * b09,"
332 " a31 * b05 - a32 * b04 + a33 * b03,"
333 " a22 * b04 - a21 * b05 - a23 * b03,"
334 " a12 * b08 - a10 * b11 - a13 * b07,"
335 " a00 * b11 - a02 * b08 + a03 * b07,"
336 " a32 * b02 - a30 * b05 - a33 * b01,"
337 " a20 * b05 - a22 * b02 + a23 * b01,"
338 " a10 * b10 - a11 * b08 + a13 * b06,"
339 " a01 * b08 - a00 * b10 - a03 * b06,"
340 " a30 * b04 - a31 * b02 + a33 * b00,"
341 " a21 * b02 - a20 * b04 - a23 * b00,"
342 " a11 * b07 - a10 * b09 - a12 * b06,"
343 " a00 * b09 - a01 * b07 + a02 * b06,"
344 " a31 * b01 - a30 * b03 - a32 * b00,"
345 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
346 "}"
347 ).c_str());
348 }
349 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500350 this->write(name);
351}
352
Timothy Liang6403b0e2018-05-17 10:40:04 -0400353void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
354 switch (kind) {
355 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400356 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400357 this->write(".sample(");
358 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
359 this->write(SAMPLER_SUFFIX);
360 this->write(", ");
Timothy Liangee84fe12018-05-18 14:38:19 -0400361 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500362 // have to store the vector in a temp variable to avoid double evaluating it
363 String tmpVar = "tmpCoord" + to_string(fVarCount++);
364 this->fFunctionHeader += " " + this->typeName(c.fArguments[1]->fType) + " " +
365 tmpVar + ";\n";
366 this->write("(" + tmpVar + " = ");
367 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
368 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400369 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400370 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500371 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400372 this->write(")");
373 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400374 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500375 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400376 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500377 String tmpX = "tmpX" + to_string(fVarCount++);
378 String tmpY = "tmpY" + to_string(fVarCount++);
379 this->fFunctionHeader += " " + this->typeName(c.fArguments[0]->fType) + " " + tmpX +
380 ", " + tmpY + ";\n";
381 this->write("(" + tmpX + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400382 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500383 this->write(", " + tmpY + " = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400384 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500385 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400386 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500387 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400388 default:
389 ABORT("unsupported special intrinsic kind");
390 }
391}
392
John Stilesfcf8cb22020-08-06 14:29:22 -0400393// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
394// Cells that don't exist in the source matrix will be populated with identity-matrix values.
395void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
396 SkASSERT(rows <= 4);
397 SkASSERT(columns <= 4);
398
399 const char* columnSeparator = "";
400 for (int c = 0; c < columns; ++c) {
401 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
402 columnSeparator = "), ";
403
404 // Determine how many values to take from the source matrix for this row.
405 int swizzleLength = 0;
406 if (c < sourceMatrix.columns()) {
407 swizzleLength = std::min<>(rows, sourceMatrix.rows());
408 }
409
410 // Emit all the values from the source matrix row.
411 bool firstItem;
412 switch (swizzleLength) {
413 case 0: firstItem = true; break;
414 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
415 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
416 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
417 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
418 default: SkUNREACHABLE;
419 }
420
421 // Emit the placeholder identity-matrix cells.
422 for (int r = swizzleLength; r < rows; ++r) {
423 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
424 firstItem = false;
425 }
426 }
427
428 fExtraFunctions.writeText(")");
429}
430
431// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
432// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
433void MetalCodeGenerator::assembleMatrixFromExpressions(
434 const std::vector<std::unique_ptr<Expression>>& args, int rows, int columns) {
435 size_t argIndex = 0;
436 int argPosition = 0;
437
438 const char* columnSeparator = "";
439 for (int c = 0; c < columns; ++c) {
440 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
441 columnSeparator = "), ";
442
443 const char* rowSeparator = "";
444 for (int r = 0; r < rows; ++r) {
445 fExtraFunctions.writeText(rowSeparator);
446 rowSeparator = ", ";
447
448 if (argIndex < args.size()) {
449 const Type& argType = args[argIndex]->fType;
Ethan Nicholase6592142020-09-08 10:22:09 -0400450 switch (argType.typeKind()) {
451 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400452 fExtraFunctions.printf("x%zu", argIndex);
453 break;
454 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400455 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400456 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
457 break;
458 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400459 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400460 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
461 argPosition / argType.rows(),
462 argPosition % argType.rows());
463 break;
464 }
465 default: {
466 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
467 fExtraFunctions.writeText("<error>");
468 break;
469 }
470 }
471
472 ++argPosition;
473 if (argPosition >= argType.columns() * argType.rows()) {
474 ++argIndex;
475 argPosition = 0;
476 }
477 } else {
478 SkDEBUGFAIL("not enough arguments for matrix constructor");
479 fExtraFunctions.writeText("<error>");
480 }
481 }
482 }
483
484 if (argPosition != 0 || argIndex != args.size()) {
485 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
486 fExtraFunctions.writeText(", <error>");
487 }
488
489 fExtraFunctions.writeText(")");
490}
491
John Stiles1bdafbf2020-05-28 12:17:20 -0400492// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
493// Keeps track of previously generated constructors so that we won't generate more than one
494// constructor for any given permutation of input argument types. Returns the name of the
495// generated constructor method.
496String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
497 const Type& matrix = c.fType;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500498 int columns = matrix.columns();
499 int rows = matrix.rows();
John Stiles1bdafbf2020-05-28 12:17:20 -0400500 const std::vector<std::unique_ptr<Expression>>& args = c.fArguments;
501
502 // Create the helper-method name and use it as our lookup key.
503 String name;
504 name.appendf("float%dx%d_from", columns, rows);
505 for (const std::unique_ptr<Expression>& expr : args) {
506 name.appendf("_%s", expr->fType.displayName().c_str());
507 }
508
509 // If a helper-method has already been synthesized, we don't need to synthesize it again.
510 auto [iter, newlyCreated] = fHelpers.insert(name);
511 if (!newlyCreated) {
512 return name;
513 }
514
515 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
516 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
517 // supply a mixture of scalars and vectors.)
518 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
519
520 size_t argIndex = 0;
521 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400522 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400523 fExtraFunctions.printf("%s%s x%zu", argSeparator,
524 expr->fType.displayName().c_str(), argIndex++);
525 argSeparator = ", ";
526 }
527
528 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
529
Ethan Nicholase6592142020-09-08 10:22:09 -0400530 if (args.size() == 1 && args.front()->fType.typeKind() == Type::TypeKind::kMatrix) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400531 this->assembleMatrixFromMatrix(args.front()->fType, rows, columns);
532 } else {
533 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400534 }
535
John Stilesfcf8cb22020-08-06 14:29:22 -0400536 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500537 return name;
538}
539
540bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
541 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
542 return false;
543 }
544 if (t1.columns() > 1) {
545 return this->canCoerce(t1.componentType(), t2.componentType());
546 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500547 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500548}
549
John Stiles1bdafbf2020-05-28 12:17:20 -0400550bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
551 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
Ethan Nicholase6592142020-09-08 10:22:09 -0400552 if (c.fType.typeKind() != Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400553 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500554 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400555
556 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
557 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
558 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
559 // scalars can be constructed trivially. In more complex cases, we generate a helper function
560 // that converts our inputs into a properly-shaped matrix.
561 // A matrix construct helper method is always used if any input argument is a matrix.
562 // Helper methods are also necessary when any argument would span multiple rows. For instance:
563 //
564 // float2 x = (1, 2);
565 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
566 // | 2 4 6 |
567 //
568 // float2 x = (2, 3);
569 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
570 // | 2 4 6 |
571 //
572 // float4 x = (1, 2, 3, 4);
573 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
574 // | 2 4 |
575 //
576
577 int position = 0;
578 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
579 // If an input argument is a matrix, we need a helper function.
Ethan Nicholase6592142020-09-08 10:22:09 -0400580 if (expr->fType.typeKind() == Type::TypeKind::kMatrix) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400581 return true;
582 }
583 position += expr->fType.columns();
584 if (position > c.fType.rows()) {
585 // An input argument would span multiple rows; a helper function is required.
586 return true;
587 }
588 if (position == c.fType.rows()) {
589 // We've advanced to the end of a row. Wrap to the start of the next row.
590 position = 0;
591 }
592 }
593
594 return false;
595}
596
597void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
598 // Handle special cases for single-argument constructors.
599 if (c.fArguments.size() == 1) {
600 // If the type is coercible, emit it directly.
601 const Expression& arg = *c.fArguments.front();
602 if (this->canCoerce(c.fType, arg.fType)) {
603 this->writeExpression(arg, parentPrecedence);
604 return;
605 }
606
607 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
608 // matrix constructor.
Ethan Nicholase6592142020-09-08 10:22:09 -0400609 if (c.fType.typeKind() == Type::TypeKind::kMatrix && arg.fType.isNumber()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400610 const Type& matrix = c.fType;
611 this->write("float");
612 this->write(to_string(matrix.columns()));
613 this->write("x");
614 this->write(to_string(matrix.rows()));
615 this->write("(");
616 this->writeExpression(arg, parentPrecedence);
617 this->write(")");
618 return;
619 }
620 }
621
622 // Emit and invoke a matrix-constructor helper method if one is necessary.
623 if (this->matrixConstructHelperIsNeeded(c)) {
624 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000625 this->write("(");
626 const char* separator = "";
John Stiles1bdafbf2020-05-28 12:17:20 -0400627 for (const std::unique_ptr<Expression>& expr : c.fArguments) {
John Stiles1fa15b12020-05-28 17:36:54 +0000628 this->write(separator);
629 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400630 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400631 }
John Stiles1fa15b12020-05-28 17:36:54 +0000632 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400633 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400634 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400635
636 // Explicitly invoke the constructor, passing in the necessary arguments.
637 this->writeType(c.fType);
638 this->write("(");
639 const char* separator = "";
640 int scalarCount = 0;
641 for (const std::unique_ptr<Expression>& arg : c.fArguments) {
642 this->write(separator);
643 separator = ", ";
Ethan Nicholase6592142020-09-08 10:22:09 -0400644 if (c.fType.typeKind() == Type::TypeKind::kMatrix &&
645 arg->fType.columns() < c.fType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400646 // Merge scalars and smaller vectors together.
647 if (!scalarCount) {
648 this->writeType(c.fType.componentType());
649 this->write(to_string(c.fType.rows()));
650 this->write("(");
651 }
652 scalarCount += arg->fType.columns();
653 }
654 this->writeExpression(*arg, kSequence_Precedence);
655 if (scalarCount && scalarCount == c.fType.rows()) {
656 this->write(")");
657 scalarCount = 0;
658 }
659 }
660 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400661}
662
663void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400664 if (fRTHeightName.length()) {
665 this->write("float4(_fragCoord.x, ");
666 this->write(fRTHeightName.c_str());
667 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500668 } else {
669 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
670 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400671}
672
673void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
674 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
675 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400676 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400677 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400678 case SK_FRAGCOORD_BUILTIN:
679 this->writeFragCoord();
680 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400681 case SK_VERTEXID_BUILTIN:
682 this->write("sk_VertexID");
683 break;
684 case SK_INSTANCEID_BUILTIN:
685 this->write("sk_InstanceID");
686 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400687 case SK_CLOCKWISE_BUILTIN:
688 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400689 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400690 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
691 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400692 default:
693 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
694 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
695 this->write("_in.");
696 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400697 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400698 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400699 ref.fVariable.fType.typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400700 this->write("_uniforms.");
701 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400702 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400703 }
704 }
Timothy Liang651286f2018-06-07 09:55:33 -0400705 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400706 }
707}
708
709void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
710 this->writeExpression(*expr.fBase, kPostfix_Precedence);
711 this->write("[");
712 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
713 this->write("]");
714}
715
716void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400717 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400718 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
719 this->writeExpression(*f.fBase, kPostfix_Precedence);
720 this->write(".");
721 }
Timothy Liang7d637782018-06-05 09:58:07 -0400722 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400723 case SK_CLIPDISTANCE_BUILTIN:
724 this->write("gl_ClipDistance");
725 break;
726 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400727 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400728 break;
729 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400730 if (field->fName == "sk_PointSize") {
731 this->write("_out->sk_PointSize");
732 } else {
733 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
734 this->write("_globals->");
735 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
736 this->write("->");
737 }
Timothy Liang651286f2018-06-07 09:55:33 -0400738 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400739 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400740 }
741}
742
743void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500744 int last = swizzle.fComponents.back();
745 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
746 this->writeType(swizzle.fType);
747 this->write("(");
748 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400749 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
750 this->write(".");
751 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500752 if (c >= 0) {
753 this->write(&("x\0y\0z\0w\0"[c * 2]));
754 }
755 }
756 if (last == SKSL_SWIZZLE_0) {
757 this->write(", 0)");
758 }
759 else if (last == SKSL_SWIZZLE_1) {
760 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400761 }
762}
763
764MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
765 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400766 case Token::Kind::TK_STAR: // fall through
767 case Token::Kind::TK_SLASH: // fall through
768 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
769 case Token::Kind::TK_PLUS: // fall through
770 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
771 case Token::Kind::TK_SHL: // fall through
772 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
773 case Token::Kind::TK_LT: // fall through
774 case Token::Kind::TK_GT: // fall through
775 case Token::Kind::TK_LTEQ: // fall through
776 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
777 case Token::Kind::TK_EQEQ: // fall through
778 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
779 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
780 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
781 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
782 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
783 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
784 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
785 case Token::Kind::TK_EQ: // fall through
786 case Token::Kind::TK_PLUSEQ: // fall through
787 case Token::Kind::TK_MINUSEQ: // fall through
788 case Token::Kind::TK_STAREQ: // fall through
789 case Token::Kind::TK_SLASHEQ: // fall through
790 case Token::Kind::TK_PERCENTEQ: // fall through
791 case Token::Kind::TK_SHLEQ: // fall through
792 case Token::Kind::TK_SHREQ: // fall through
793 case Token::Kind::TK_LOGICALANDEQ: // fall through
794 case Token::Kind::TK_LOGICALXOREQ: // fall through
795 case Token::Kind::TK_LOGICALOREQ: // fall through
796 case Token::Kind::TK_BITWISEANDEQ: // fall through
797 case Token::Kind::TK_BITWISEXOREQ: // fall through
798 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
799 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400800 default: ABORT("unsupported binary operator");
801 }
802}
803
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500804void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
805 const Type& result) {
806 String key = "TimesEqual" + left.name() + right.name();
807 if (fHelpers.find(key) == fHelpers.end()) {
808 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
809 " left = left * right;\n"
810 " return left;\n"
811 "}", result.name().c_str(), left.name().c_str(),
812 right.name().c_str());
813 }
814}
815
Ethan Nicholascc305772017-10-13 16:17:45 -0400816void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
817 Precedence parentPrecedence) {
818 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500819 bool needParens = precedence >= parentPrecedence;
820 switch (b.fOperator) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400821 case Token::Kind::TK_EQEQ:
Ethan Nicholase6592142020-09-08 10:22:09 -0400822 if (b.fLeft->fType.typeKind() == Type::TypeKind::kVector) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500823 this->write("all");
824 needParens = true;
825 }
826 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400827 case Token::Kind::TK_NEQ:
Ethan Nicholase6592142020-09-08 10:22:09 -0400828 if (b.fLeft->fType.typeKind() == Type::TypeKind::kVector) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400829 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500830 needParens = true;
831 }
832 break;
833 default:
834 break;
835 }
836 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400837 this->write("(");
838 }
839 if (Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400840 Expression::Kind::kVariableReference == b.fLeft->kind() &&
Ethan Nicholascc305772017-10-13 16:17:45 -0400841 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
842 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
843 // writing to an out parameter. Since we have to turn those into pointers, we have to
844 // dereference it here.
845 this->write("*");
846 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400847 if (b.fOperator == Token::Kind::TK_STAREQ &&
848 b.fLeft->fType.typeKind() == Type::TypeKind::kMatrix &&
849 b.fRight->fType.typeKind() == Type::TypeKind::kMatrix) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500850 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
851 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400852 this->writeExpression(*b.fLeft, precedence);
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400853 if (b.fOperator != Token::Kind::TK_EQ && Compiler::IsAssignment(b.fOperator) &&
Ethan Nicholase6592142020-09-08 10:22:09 -0400854 b.fLeft->kind() == Expression::Kind::kSwizzle && !b.fLeft->hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400855 // This doesn't compile in Metal:
856 // float4 x = float4(1);
857 // x.xy *= float2x2(...);
858 // with the error message "non-const reference cannot bind to vector element",
859 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
860 // as long as the LHS has no side effects, and hope for the best otherwise.
861 this->write(" = ");
862 this->writeExpression(*b.fLeft, kAssignment_Precedence);
863 this->write(" ");
864 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400865 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400866 this->write(op.substr(0, op.size() - 1).c_str());
867 this->write(" ");
868 } else {
869 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
870 }
871 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500872 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400873 this->write(")");
874 }
875}
876
877void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
878 Precedence parentPrecedence) {
879 if (kTernary_Precedence >= parentPrecedence) {
880 this->write("(");
881 }
882 this->writeExpression(*t.fTest, kTernary_Precedence);
883 this->write(" ? ");
884 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
885 this->write(" : ");
886 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
887 if (kTernary_Precedence >= parentPrecedence) {
888 this->write(")");
889 }
890}
891
892void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
893 Precedence parentPrecedence) {
894 if (kPrefix_Precedence >= parentPrecedence) {
895 this->write("(");
896 }
897 this->write(Compiler::OperatorName(p.fOperator));
898 this->writeExpression(*p.fOperand, kPrefix_Precedence);
899 if (kPrefix_Precedence >= parentPrecedence) {
900 this->write(")");
901 }
902}
903
904void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
905 Precedence parentPrecedence) {
906 if (kPostfix_Precedence >= parentPrecedence) {
907 this->write("(");
908 }
909 this->writeExpression(*p.fOperand, kPostfix_Precedence);
910 this->write(Compiler::OperatorName(p.fOperator));
911 if (kPostfix_Precedence >= parentPrecedence) {
912 this->write(")");
913 }
914}
915
916void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
917 this->write(b.fValue ? "true" : "false");
918}
919
920void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
921 if (i.fType == *fContext.fUInt_Type) {
922 this->write(to_string(i.fValue & 0xffffffff) + "u");
923 } else {
924 this->write(to_string((int32_t) i.fValue));
925 }
926}
927
928void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
929 this->write(to_string(f.fValue));
930}
931
932void MetalCodeGenerator::writeSetting(const Setting& s) {
933 ABORT("internal error; setting was not folded to a constant during compilation\n");
934}
935
936void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400937 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400938 const char* separator = "";
939 if ("main" == f.fDeclaration.fName) {
940 switch (fProgram.fKind) {
941 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400942 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400943 break;
944 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400945 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -0400946 break;
947 default:
John Stilesf7d70432020-05-28 15:46:38 -0400948 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -0400949 }
950 this->write("(Inputs _in [[stage_in]]");
951 if (-1 != fUniformBuffer) {
952 this->write(", constant Uniforms& _uniforms [[buffer(" +
953 to_string(fUniformBuffer) + ")]]");
954 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400955 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400956 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles3dc0da62020-08-19 17:48:31 -0400957 const VarDeclarations& decls = e.as<VarDeclarations>();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400958 if (!decls.fVars.size()) {
959 continue;
960 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400961 for (const auto& stmt: decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -0400962 VarDeclaration& var = stmt->as<VarDeclaration>();
Ethan Nicholase6592142020-09-08 10:22:09 -0400963 if (var.fVar->fType.typeKind() == Type::TypeKind::kSampler) {
John Stiles08cb2c12020-07-06 10:18:49 -0400964 if (var.fVar->fModifiers.fLayout.fBinding < 0) {
965 fErrors.error(decls.fOffset,
966 "Metal samplers must have 'layout(binding=...)'");
967 }
Timothy Liang7d637782018-06-05 09:58:07 -0400968 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400969 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400970 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400971 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
972 this->write(")]]");
973 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400974 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400975 this->write(SAMPLER_SUFFIX);
976 this->write("[[sampler(");
977 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400978 this->write(")]]");
979 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400980 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400981 } else if (e.kind() == ProgramElement::Kind::kInterfaceBlock) {
Timothy Lianga06f2152018-05-24 15:33:31 -0400982 InterfaceBlock& intf = (InterfaceBlock&) e;
983 if ("sk_PerVertex" == intf.fTypeName) {
984 continue;
985 }
986 this->write(", constant ");
987 this->writeType(intf.fVariable.fType);
988 this->write("& " );
989 this->write(fInterfaceBlockNameMap[&intf]);
990 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400991 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -0400992 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400993 }
994 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500995 if (fProgram.fKind == Program::kFragment_Kind) {
996 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400997 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -0400998 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400999 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001000 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001001 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001002 } else if (fProgram.fKind == Program::kVertex_Kind) {
1003 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001004 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001005 separator = ", ";
1006 } else {
1007 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -04001008 this->write(" ");
1009 this->writeName(f.fDeclaration.fName);
1010 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001011 Requirements requirements = this->requirements(f.fDeclaration);
1012 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001013 this->write("Inputs _in");
1014 separator = ", ";
1015 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001016 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001017 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001018 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001019 separator = ", ";
1020 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001021 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001022 this->write(separator);
1023 this->write("Uniforms _uniforms");
1024 separator = ", ";
1025 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001026 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001027 this->write(separator);
1028 this->write("thread Globals* _globals");
1029 separator = ", ";
1030 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001031 if (requirements & kFragCoord_Requirement) {
1032 this->write(separator);
1033 this->write("float4 _fragCoord");
1034 separator = ", ";
1035 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001036 }
1037 for (const auto& param : f.fDeclaration.fParameters) {
1038 this->write(separator);
1039 separator = ", ";
1040 this->writeModifiers(param->fModifiers, false);
1041 std::vector<int> sizes;
1042 const Type* type = &param->fType;
Ethan Nicholase6592142020-09-08 10:22:09 -04001043 while (type->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001044 sizes.push_back(type->columns());
1045 type = &type->componentType();
1046 }
1047 this->writeType(*type);
1048 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
1049 this->write("*");
1050 }
Timothy Liang651286f2018-06-07 09:55:33 -04001051 this->write(" ");
1052 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001053 for (int s : sizes) {
1054 if (s <= 0) {
1055 this->write("[]");
1056 } else {
1057 this->write("[" + to_string(s) + "]");
1058 }
1059 }
1060 }
1061 this->writeLine(") {");
1062
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001063 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001064
Ethan Nicholascc305772017-10-13 16:17:45 -04001065 if ("main" == f.fDeclaration.fName) {
John Stilescdcdb042020-07-06 09:03:51 -04001066 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001067 this->writeLine(" Outputs _outputStruct;");
1068 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001069 }
John Stilesc67b3622020-05-28 17:53:13 -04001070
Ethan Nicholascc305772017-10-13 16:17:45 -04001071 fFunctionHeader = "";
1072 OutputStream* oldOut = fOut;
1073 StringStream buffer;
1074 fOut = &buffer;
1075 fIndentation++;
1076 this->writeStatements(((Block&) *f.fBody).fStatements);
1077 if ("main" == f.fDeclaration.fName) {
1078 switch (fProgram.fKind) {
1079 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001080 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001081 break;
1082 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001083 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -04001084 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -04001085 break;
1086 default:
John Stilesf7d70432020-05-28 15:46:38 -04001087 SkDEBUGFAIL("unsupported kind of program");
Ethan Nicholascc305772017-10-13 16:17:45 -04001088 }
1089 }
1090 fIndentation--;
1091 this->writeLine("}");
1092
1093 fOut = oldOut;
1094 this->write(fFunctionHeader);
1095 this->write(buffer.str());
1096}
1097
1098void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1099 bool globalContext) {
1100 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1101 this->write("thread ");
1102 }
1103 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001104 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001105 }
1106}
1107
1108void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1109 if ("sk_PerVertex" == intf.fTypeName) {
1110 return;
1111 }
1112 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001113 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001114 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001115 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001116 fWrittenStructs.push_back(structType);
Ethan Nicholase6592142020-09-08 10:22:09 -04001117 while (structType->typeKind() == Type::TypeKind::kArray) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001118 structType = &structType->componentType();
1119 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001120 fIndentation++;
1121 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001122 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001123 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001124 }
1125 fIndentation--;
1126 this->write("}");
1127 if (intf.fInstanceName.size()) {
1128 this->write(" ");
1129 this->write(intf.fInstanceName);
1130 for (const auto& size : intf.fSizes) {
1131 this->write("[");
1132 if (size) {
1133 this->writeExpression(*size, kTopLevel_Precedence);
1134 }
1135 this->write("]");
1136 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001137 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1138 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001139 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001140 }
1141 this->writeLine(";");
1142}
1143
Timothy Liangdc89f192018-06-13 09:20:31 -04001144void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1145 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001146 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001147 int currentOffset = 0;
1148 for (const auto& field: fields) {
1149 int fieldOffset = field.fModifiers.fLayout.fOffset;
1150 const Type* fieldType = field.fType;
1151 if (fieldOffset != -1) {
1152 if (currentOffset > fieldOffset) {
1153 fErrors.error(parentOffset,
1154 "offset of field '" + field.fName + "' must be at least " +
1155 to_string((int) currentOffset));
1156 } else if (currentOffset < fieldOffset) {
1157 this->write("char pad");
1158 this->write(to_string(fPaddingCount++));
1159 this->write("[");
1160 this->write(to_string(fieldOffset - currentOffset));
1161 this->writeLine("];");
1162 currentOffset = fieldOffset;
1163 }
1164 int alignment = memoryLayout.alignment(*fieldType);
1165 if (fieldOffset % alignment) {
1166 fErrors.error(parentOffset,
1167 "offset of field '" + field.fName + "' must be a multiple of " +
1168 to_string((int) alignment));
1169 }
1170 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001171 currentOffset += memoryLayout.size(*fieldType);
1172 std::vector<int> sizes;
Ethan Nicholase6592142020-09-08 10:22:09 -04001173 while (fieldType->typeKind() == Type::TypeKind::kArray) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001174 sizes.push_back(fieldType->columns());
1175 fieldType = &fieldType->componentType();
1176 }
1177 this->writeModifiers(field.fModifiers, false);
1178 this->writeType(*fieldType);
1179 this->write(" ");
1180 this->writeName(field.fName);
1181 for (int s : sizes) {
1182 if (s <= 0) {
1183 this->write("[]");
1184 } else {
1185 this->write("[" + to_string(s) + "]");
1186 }
1187 }
1188 this->writeLine(";");
1189 if (parentIntf) {
1190 fInterfaceBlockMap[&field] = parentIntf;
1191 }
1192 }
1193}
1194
Ethan Nicholascc305772017-10-13 16:17:45 -04001195void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1196 this->writeExpression(value, kTopLevel_Precedence);
1197}
1198
Timothy Liang651286f2018-06-07 09:55:33 -04001199void MetalCodeGenerator::writeName(const String& name) {
1200 if (fReservedWords.find(name) != fReservedWords.end()) {
1201 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1202 }
1203 this->write(name);
1204}
1205
Ethan Nicholascc305772017-10-13 16:17:45 -04001206void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001207 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001208 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001209 for (const auto& stmt : decl.fVars) {
1210 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001211 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001212 continue;
1213 }
1214 if (wroteType) {
1215 this->write(", ");
1216 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001217 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001218 this->writeType(decl.fBaseType);
1219 this->write(" ");
1220 wroteType = true;
1221 }
Timothy Liang651286f2018-06-07 09:55:33 -04001222 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001223 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001224 this->write("[");
1225 if (size) {
1226 this->writeExpression(*size, kTopLevel_Precedence);
1227 }
1228 this->write("]");
1229 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001230 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001231 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001232 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001233 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001234 }
1235 if (wroteType) {
1236 this->write(";");
1237 }
1238}
1239
1240void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001241 switch (s.kind()) {
1242 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001243 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001244 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001245 case Statement::Kind::kExpression:
John Stiles26f98502020-08-18 09:30:51 -04001246 this->writeExpression(*s.as<ExpressionStatement>().fExpression, kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001247 this->write(";");
1248 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001249 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001250 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001251 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001252 case Statement::Kind::kVarDeclarations:
John Stiles26f98502020-08-18 09:30:51 -04001253 this->writeVarDeclarations(*s.as<VarDeclarationsStatement>().fDeclaration, false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001254 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001255 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001256 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001257 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001258 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001259 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001260 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001261 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001262 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001263 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001264 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001265 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001266 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001267 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001268 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001269 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001270 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001271 this->write("break;");
1272 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001273 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001274 this->write("continue;");
1275 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001276 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001277 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001278 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001279 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001280 this->write(";");
1281 break;
1282 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001283#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001284 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001285#endif
1286 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001287 }
1288}
1289
1290void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1291 for (const auto& s : statements) {
1292 if (!s->isEmpty()) {
1293 this->writeStatement(*s);
1294 this->writeLine();
1295 }
1296 }
1297}
1298
1299void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001300 if (b.fIsScope) {
1301 this->writeLine("{");
1302 fIndentation++;
1303 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001304 this->writeStatements(b.fStatements);
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001305 if (b.fIsScope) {
1306 fIndentation--;
1307 this->write("}");
1308 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001309}
1310
1311void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1312 this->write("if (");
1313 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1314 this->write(") ");
1315 this->writeStatement(*stmt.fIfTrue);
1316 if (stmt.fIfFalse) {
1317 this->write(" else ");
1318 this->writeStatement(*stmt.fIfFalse);
1319 }
1320}
1321
1322void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1323 this->write("for (");
1324 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1325 this->writeStatement(*f.fInitializer);
1326 } else {
1327 this->write("; ");
1328 }
1329 if (f.fTest) {
1330 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1331 }
1332 this->write("; ");
1333 if (f.fNext) {
1334 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1335 }
1336 this->write(") ");
1337 this->writeStatement(*f.fStatement);
1338}
1339
1340void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1341 this->write("while (");
1342 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1343 this->write(") ");
1344 this->writeStatement(*w.fStatement);
1345}
1346
1347void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1348 this->write("do ");
1349 this->writeStatement(*d.fStatement);
1350 this->write(" while (");
1351 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1352 this->write(");");
1353}
1354
1355void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1356 this->write("switch (");
1357 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1358 this->writeLine(") {");
1359 fIndentation++;
1360 for (const auto& c : s.fCases) {
1361 if (c->fValue) {
1362 this->write("case ");
1363 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1364 this->writeLine(":");
1365 } else {
1366 this->writeLine("default:");
1367 }
1368 fIndentation++;
1369 for (const auto& stmt : c->fStatements) {
1370 this->writeStatement(*stmt);
1371 this->writeLine();
1372 }
1373 fIndentation--;
1374 }
1375 fIndentation--;
1376 this->write("}");
1377}
1378
1379void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1380 this->write("return");
1381 if (r.fExpression) {
1382 this->write(" ");
1383 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1384 }
1385 this->write(";");
1386}
1387
1388void MetalCodeGenerator::writeHeader() {
1389 this->write("#include <metal_stdlib>\n");
1390 this->write("#include <simd/simd.h>\n");
1391 this->write("using namespace metal;\n");
1392}
1393
1394void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001395 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001396 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles3dc0da62020-08-19 17:48:31 -04001397 const VarDeclarations& decls = e.as<VarDeclarations>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001398 if (!decls.fVars.size()) {
1399 continue;
1400 }
John Stiles3dc0da62020-08-19 17:48:31 -04001401 const Variable& first = *decls.fVars[0]->as<VarDeclaration>().fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001402 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholase6592142020-09-08 10:22:09 -04001403 first.fType.typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001404 if (-1 == fUniformBuffer) {
1405 this->write("struct Uniforms {\n");
1406 fUniformBuffer = first.fModifiers.fLayout.fSet;
1407 if (-1 == fUniformBuffer) {
1408 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1409 }
1410 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1411 if (-1 == fUniformBuffer) {
1412 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1413 "the same 'layout(set=...)'");
1414 }
1415 }
1416 this->write(" ");
1417 this->writeType(first.fType);
1418 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001419 for (const auto& stmt : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001420 const VarDeclaration& var = stmt->as<VarDeclaration>();
Timothy Liang651286f2018-06-07 09:55:33 -04001421 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001422 }
1423 this->write(";\n");
1424 }
1425 }
1426 }
1427 if (-1 != fUniformBuffer) {
1428 this->write("};\n");
1429 }
1430}
1431
1432void MetalCodeGenerator::writeInputStruct() {
1433 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001434 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001435 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles3dc0da62020-08-19 17:48:31 -04001436 const VarDeclarations& decls = e.as<VarDeclarations>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001437 if (!decls.fVars.size()) {
1438 continue;
1439 }
John Stiles3dc0da62020-08-19 17:48:31 -04001440 const Variable& first = *decls.fVars[0]->as<VarDeclaration>().fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001441 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1442 -1 == first.fModifiers.fLayout.fBuiltin) {
1443 this->write(" ");
1444 this->writeType(first.fType);
1445 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001446 for (const auto& stmt : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001447 const VarDeclaration& var = stmt->as<VarDeclaration>();
Timothy Liang651286f2018-06-07 09:55:33 -04001448 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001449 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001450 if (fProgram.fKind == Program::kVertex_Kind) {
1451 this->write(" [[attribute(" +
1452 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1453 } else if (fProgram.fKind == Program::kFragment_Kind) {
1454 this->write(" [[user(locn" +
1455 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1456 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001457 }
1458 }
1459 this->write(";\n");
1460 }
1461 }
1462 }
1463 this->write("};\n");
1464}
1465
1466void MetalCodeGenerator::writeOutputStruct() {
1467 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001468 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001469 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001470 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001471 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001472 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001473 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001474 if (e.kind() == ProgramElement::Kind::kVar) {
John Stiles3dc0da62020-08-19 17:48:31 -04001475 const VarDeclarations& decls = e.as<VarDeclarations>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001476 if (!decls.fVars.size()) {
1477 continue;
1478 }
John Stiles3dc0da62020-08-19 17:48:31 -04001479 const Variable& first = *decls.fVars[0]->as<VarDeclaration>().fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001480 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1481 -1 == first.fModifiers.fLayout.fBuiltin) {
1482 this->write(" ");
1483 this->writeType(first.fType);
1484 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001485 for (const auto& stmt : decls.fVars) {
John Stiles3dc0da62020-08-19 17:48:31 -04001486 const VarDeclaration& var = stmt->as<VarDeclaration>();
Timothy Liang651286f2018-06-07 09:55:33 -04001487 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001488 if (fProgram.fKind == Program::kVertex_Kind) {
1489 this->write(" [[user(locn" +
1490 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1491 } else if (fProgram.fKind == Program::kFragment_Kind) {
1492 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001493 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1494 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1495 if (colorIndex) {
1496 this->write(", index(" + to_string(colorIndex) + ")");
1497 }
1498 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001499 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001500 }
1501 this->write(";\n");
1502 }
1503 }
Timothy Liang7d637782018-06-05 09:58:07 -04001504 }
1505 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001506 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001507 }
1508 this->write("};\n");
1509}
1510
1511void MetalCodeGenerator::writeInterfaceBlocks() {
1512 bool wroteInterfaceBlock = false;
1513 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001514 if (e.kind() == ProgramElement::Kind::kInterfaceBlock) {
John Stiles3dc0da62020-08-19 17:48:31 -04001515 this->writeInterfaceBlock(e.as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001516 wroteInterfaceBlock = true;
1517 }
1518 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001519 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001520 this->writeLine("struct sksl_synthetic_uniforms {");
1521 this->writeLine(" float u_skRTHeight;");
1522 this->writeLine("};");
1523 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001524}
1525
John Stilescdcdb042020-07-06 09:03:51 -04001526void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1527 // Visit the interface blocks.
1528 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
1529 visitor->VisitInterfaceBlock(*interfaceType, interfaceName);
1530 }
1531 for (const ProgramElement& element : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001532 if (element.kind() != ProgramElement::Kind::kVar) {
John Stilescdcdb042020-07-06 09:03:51 -04001533 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001534 }
John Stilescdcdb042020-07-06 09:03:51 -04001535 const VarDeclarations& decls = static_cast<const VarDeclarations&>(element);
1536 if (decls.fVars.empty()) {
1537 continue;
1538 }
1539 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
1540 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
Ethan Nicholase6592142020-09-08 10:22:09 -04001541 first.fType.typeKind() == Type::TypeKind::kSampler) {
John Stilescdcdb042020-07-06 09:03:51 -04001542 for (const auto& stmt : decls.fVars) {
1543 VarDeclaration& var = static_cast<VarDeclaration&>(*stmt);
John Stilesc67b3622020-05-28 17:53:13 -04001544
Ethan Nicholase6592142020-09-08 10:22:09 -04001545 if (var.fVar->fType.typeKind() == Type::TypeKind::kSampler) {
John Stilescdcdb042020-07-06 09:03:51 -04001546 // Samplers are represented as a "texture/sampler" duo in the global struct.
1547 visitor->VisitTexture(first.fType, var.fVar->fName);
1548 visitor->VisitSampler(first.fType, String(var.fVar->fName) + SAMPLER_SUFFIX);
1549 } else {
1550 // Visit a regular variable.
1551 visitor->VisitVariable(*var.fVar, var.fValue.get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001552 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001553 }
1554 }
1555 }
John Stilescdcdb042020-07-06 09:03:51 -04001556}
1557
1558void MetalCodeGenerator::writeGlobalStruct() {
1559 class : public GlobalStructVisitor {
1560 public:
1561 void VisitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
1562 this->AddElement();
1563 fCodeGen->write(" constant ");
1564 fCodeGen->write(block.fTypeName);
1565 fCodeGen->write("* ");
1566 fCodeGen->writeName(blockName);
1567 fCodeGen->write(";\n");
1568 }
1569 void VisitTexture(const Type& type, const String& name) override {
1570 this->AddElement();
1571 fCodeGen->write(" ");
1572 fCodeGen->writeType(type);
1573 fCodeGen->write(" ");
1574 fCodeGen->writeName(name);
1575 fCodeGen->write(";\n");
1576 }
1577 void VisitSampler(const Type&, const String& name) override {
1578 this->AddElement();
1579 fCodeGen->write(" sampler ");
1580 fCodeGen->writeName(name);
1581 fCodeGen->write(";\n");
1582 }
1583 void VisitVariable(const Variable& var, const Expression* value) override {
1584 this->AddElement();
1585 fCodeGen->write(" ");
1586 fCodeGen->writeType(var.fType);
1587 fCodeGen->write(" ");
1588 fCodeGen->writeName(var.fName);
1589 fCodeGen->write(";\n");
1590 }
1591 void AddElement() {
1592 if (fFirst) {
1593 fCodeGen->write("struct Globals {\n");
1594 fFirst = false;
1595 }
1596 }
1597 void Finish() {
1598 if (!fFirst) {
1599 fCodeGen->write("};");
1600 fFirst = true;
1601 }
1602 }
1603
1604 MetalCodeGenerator* fCodeGen = nullptr;
1605 bool fFirst = true;
1606 } visitor;
1607
1608 visitor.fCodeGen = this;
1609 this->visitGlobalStruct(&visitor);
1610 visitor.Finish();
1611}
1612
1613void MetalCodeGenerator::writeGlobalInit() {
1614 class : public GlobalStructVisitor {
1615 public:
1616 void VisitInterfaceBlock(const InterfaceBlock& blockType,
1617 const String& blockName) override {
1618 this->AddElement();
1619 fCodeGen->write("&");
1620 fCodeGen->writeName(blockName);
1621 }
1622 void VisitTexture(const Type&, const String& name) override {
1623 this->AddElement();
1624 fCodeGen->writeName(name);
1625 }
1626 void VisitSampler(const Type&, const String& name) override {
1627 this->AddElement();
1628 fCodeGen->writeName(name);
1629 }
1630 void VisitVariable(const Variable& var, const Expression* value) override {
1631 this->AddElement();
1632 if (value) {
1633 fCodeGen->writeVarInitializer(var, *value);
1634 } else {
1635 fCodeGen->write("{}");
1636 }
1637 }
1638 void AddElement() {
1639 if (fFirst) {
1640 fCodeGen->write(" Globals globalStruct{");
1641 fFirst = false;
1642 } else {
1643 fCodeGen->write(", ");
1644 }
1645 }
1646 void Finish() {
1647 if (!fFirst) {
1648 fCodeGen->writeLine("};");
1649 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1650 fCodeGen->writeLine(" (void)_globals;");
1651 }
1652 }
1653 MetalCodeGenerator* fCodeGen = nullptr;
1654 bool fFirst = true;
1655 } visitor;
1656
1657 visitor.fCodeGen = this;
1658 this->visitGlobalStruct(&visitor);
1659 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001660}
1661
Ethan Nicholascc305772017-10-13 16:17:45 -04001662void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001663 switch (e.kind()) {
1664 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001665 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001666 case ProgramElement::Kind::kVar: {
John Stiles3dc0da62020-08-19 17:48:31 -04001667 const VarDeclarations& decl = e.as<VarDeclarations>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001668 if (decl.fVars.size() > 0) {
John Stiles3dc0da62020-08-19 17:48:31 -04001669 int builtin = decl.fVars[0]->as<VarDeclaration>().fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001670 if (-1 == builtin) {
1671 // normal var
1672 this->writeVarDeclarations(decl, true);
1673 this->writeLine();
1674 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1675 // ignore
1676 }
1677 }
1678 break;
1679 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001680 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001681 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001682 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001683 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001684 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001685 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001686 case ProgramElement::Kind::kModifiers:
John Stiles3dc0da62020-08-19 17:48:31 -04001687 this->writeModifiers(e.as<ModifiersDeclaration>().fModifiers, true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001688 this->writeLine(";");
1689 break;
1690 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001691#ifdef SK_DEBUG
1692 ABORT("unsupported program element: %s\n", e.description().c_str());
1693#endif
1694 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001695 }
1696}
1697
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001698MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1699 if (!e) {
1700 return kNo_Requirements;
1701 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001702 switch (e->kind()) {
1703 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001704 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001705 Requirements result = this->requirements(f.fFunction);
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001706 for (const auto& arg : f.fArguments) {
1707 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001708 }
1709 return result;
1710 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001711 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001712 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001713 Requirements result = kNo_Requirements;
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001714 for (const auto& arg : c.fArguments) {
1715 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::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001720 const FieldAccess& f = e->as<FieldAccess>();
Timothy Liang7d637782018-06-05 09:58:07 -04001721 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1722 return kGlobals_Requirement;
1723 }
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001724 return this->requirements(f.fBase.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001725 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001726 case Expression::Kind::kSwizzle:
John Stiles3dc0da62020-08-19 17:48:31 -04001727 return this->requirements(e->as<Swizzle>().fBase.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001728 case Expression::Kind::kBinary: {
1729 const BinaryExpression& bin = e->as<BinaryExpression>();
1730 return this->requirements(bin.fLeft.get()) |
1731 this->requirements(bin.fRight.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001732 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001733 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001734 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001735 return this->requirements(idx.fBase.get()) | this->requirements(idx.fIndex.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001736 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001737 case Expression::Kind::kPrefix:
John Stiles3dc0da62020-08-19 17:48:31 -04001738 return this->requirements(e->as<PrefixExpression>().fOperand.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001739 case Expression::Kind::kPostfix:
John Stiles3dc0da62020-08-19 17:48:31 -04001740 return this->requirements(e->as<PostfixExpression>().fOperand.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001741 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001742 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001743 return this->requirements(t.fTest.get()) | this->requirements(t.fIfTrue.get()) |
1744 this->requirements(t.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001745 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001746 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001747 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001748 Requirements result = kNo_Requirements;
1749 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001750 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001751 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1752 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1753 result = kInputs_Requirement;
1754 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1755 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001756 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholase6592142020-09-08 10:22:09 -04001757 v.fVariable.fType.typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001758 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001759 } else {
1760 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 }
1762 }
1763 return result;
1764 }
1765 default:
1766 return kNo_Requirements;
1767 }
1768}
1769
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001770MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1771 if (!s) {
1772 return kNo_Requirements;
1773 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001774 switch (s->kind()) {
1775 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001776 Requirements result = kNo_Requirements;
John Stiles3dc0da62020-08-19 17:48:31 -04001777 for (const auto& child : s->as<Block>().fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001778 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001779 }
1780 return result;
1781 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001782 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001783 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001784 return this->requirements(var.fValue.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001785 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001786 case Statement::Kind::kVarDeclarations: {
Timothy Liang7d637782018-06-05 09:58:07 -04001787 Requirements result = kNo_Requirements;
John Stiles3dc0da62020-08-19 17:48:31 -04001788 const VarDeclarations& decls = *s->as<VarDeclarationsStatement>().fDeclaration;
Timothy Liang7d637782018-06-05 09:58:07 -04001789 for (const auto& stmt : decls.fVars) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001790 result |= this->requirements(stmt.get());
Timothy Liang7d637782018-06-05 09:58:07 -04001791 }
1792 return result;
1793 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001794 case Statement::Kind::kExpression:
John Stiles3dc0da62020-08-19 17:48:31 -04001795 return this->requirements(s->as<ExpressionStatement>().fExpression.get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001796 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001797 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001798 return this->requirements(r.fExpression.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001799 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001800 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001801 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001802 return this->requirements(i.fTest.get()) |
1803 this->requirements(i.fIfTrue.get()) |
1804 this->requirements(i.fIfFalse.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001805 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001806 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001807 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001808 return this->requirements(f.fInitializer.get()) |
1809 this->requirements(f.fTest.get()) |
1810 this->requirements(f.fNext.get()) |
1811 this->requirements(f.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001813 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001814 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001815 return this->requirements(w.fTest.get()) |
1816 this->requirements(w.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001817 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001818 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001819 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001820 return this->requirements(d.fTest.get()) |
1821 this->requirements(d.fStatement.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001822 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001823 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001824 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001825 Requirements result = this->requirements(sw.fValue.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001826 for (const auto& c : sw.fCases) {
1827 for (const auto& st : c->fStatements) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001828 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001829 }
1830 }
1831 return result;
1832 }
1833 default:
1834 return kNo_Requirements;
1835 }
1836}
1837
1838MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1839 if (f.fBuiltin) {
1840 return kNo_Requirements;
1841 }
1842 auto found = fRequirements.find(&f);
1843 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001844 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001845 for (const auto& e : fProgram) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001846 if (e.kind() == ProgramElement::Kind::kFunction) {
John Stiles3dc0da62020-08-19 17:48:31 -04001847 const FunctionDefinition& def = e.as<FunctionDefinition>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 if (&def.fDeclaration == &f) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001849 Requirements reqs = this->requirements(def.fBody.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001850 fRequirements[&f] = reqs;
1851 return reqs;
1852 }
1853 }
1854 }
1855 }
1856 return found->second;
1857}
1858
Timothy Liangb8eeb802018-07-23 16:46:16 -04001859bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001860 OutputStream* rawOut = fOut;
1861 fOut = &fHeader;
1862 fProgramKind = fProgram.fKind;
1863 this->writeHeader();
1864 this->writeUniformStruct();
1865 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001866 this->writeOutputStruct();
1867 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001868 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001869 StringStream body;
1870 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001871 for (const auto& e : fProgram) {
1872 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001873 }
1874 fOut = rawOut;
1875
1876 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001877 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001878 write_stringstream(body, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001879 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001880}
1881
John Stilesa6841be2020-08-06 14:11:56 -04001882} // namespace SkSL