blob: 1ba9b3eaca021cc29934636f31b06d6b83a0eb76 [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
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/ir/SkSLExpressionStatement.h"
14#include "src/sksl/ir/SkSLExtension.h"
15#include "src/sksl/ir/SkSLIndexExpression.h"
16#include "src/sksl/ir/SkSLModifiersDeclaration.h"
17#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050018#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040020
Brian Osmanc262a122020-08-06 16:34:34 -040021#include <algorithm>
22
Ethan Nicholascc305772017-10-13 16:17:45 -040023namespace SkSL {
24
John Stilesd6449e92020-11-30 09:13:23 -050025const char* MetalCodeGenerator::OperatorName(Token::Kind op) {
26 switch (op) {
27 case Token::Kind::TK_LOGICALXOR: return "!=";
28 default: return Compiler::OperatorName(op);
29 }
30}
31
John Stilescdcdb042020-07-06 09:03:51 -040032class MetalCodeGenerator::GlobalStructVisitor {
33public:
34 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050035 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
36 virtual void visitTexture(const Type& type, const String& name) = 0;
37 virtual void visitSampler(const Type& type, const String& name) = 0;
38 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040039};
40
Timothy Liangee84fe12018-05-18 14:38:19 -040041void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040042#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
43#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Brian Osman46787d52020-11-24 14:18:23 -050044 fIntrinsicMap[String("distance")] = SPECIAL(Distance);
45 fIntrinsicMap[String("dot")] = SPECIAL(Dot);
46 fIntrinsicMap[String("length")] = SPECIAL(Length);
Timothy Liang651286f2018-06-07 09:55:33 -040047 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Brian Osman46787d52020-11-24 14:18:23 -050048 fIntrinsicMap[String("normalize")] = SPECIAL(Normalize);
49 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050050 fIntrinsicMap[String("equal")] = METAL(Equal);
51 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040052 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
53 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
54 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
55 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040056}
57
Ethan Nicholascc305772017-10-13 16:17:45 -040058void MetalCodeGenerator::write(const char* s) {
59 if (!s[0]) {
60 return;
61 }
62 if (fAtLineStart) {
63 for (int i = 0; i < fIndentation; i++) {
64 fOut->writeText(" ");
65 }
66 }
67 fOut->writeText(s);
68 fAtLineStart = false;
69}
70
71void MetalCodeGenerator::writeLine(const char* s) {
72 this->write(s);
73 fOut->writeText(fLineEnding);
74 fAtLineStart = true;
75}
76
77void MetalCodeGenerator::write(const String& s) {
78 this->write(s.c_str());
79}
80
81void MetalCodeGenerator::writeLine(const String& s) {
82 this->writeLine(s.c_str());
83}
84
85void MetalCodeGenerator::writeLine() {
86 this->writeLine("");
87}
88
89void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040090 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040091}
92
Ethan Nicholas45fa8102020-01-13 10:58:49 -050093String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040094 switch (type.typeKind()) {
95 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050096 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -040097 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050098 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
99 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -0400100 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500101 return "texture2d<float>"; // FIXME - support other texture types;
John Stilesfd41d872020-11-25 22:39:45 -0500102 case Type::TypeKind::kEnum:
103 return "int";
Ethan Nicholascc305772017-10-13 16:17:45 -0400104 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400105 if (type == *fContext.fHalf_Type) {
106 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500107 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -0400108 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500109 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -0400110 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500111 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400112 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500113 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400114 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400115 }
116}
117
John Stilesdc75a972020-11-25 16:24:55 -0500118bool MetalCodeGenerator::writeStructDefinition(const Type& type) {
119 for (const Type* search : fWrittenStructs) {
120 if (*search == type) {
121 // already written
122 return false;
123 }
124 }
125 fWrittenStructs.push_back(&type);
126 this->writeLine("struct " + type.name() + " {");
127 fIndentation++;
128 this->writeFields(type.fields(), type.fOffset);
129 fIndentation--;
130 this->write("}");
131 return true;
132}
133
John Stiles3dba3ee2020-12-02 23:35:49 -0500134// Flags an error if an array type is found. Meant to be used in places where an array type might
135// appear in the SkSL/IR, but can't be represented by Metal.
136void MetalCodeGenerator::disallowArrayTypes(const Type& type) {
John Stilesc0c51062020-12-03 17:16:29 -0500137 if (type.isArray()) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500138 fErrors.error(type.fOffset, "Metal does not support array types in this context");
139 }
140}
141
142// Writes the base type, stripping array suffixes. e.g. `float[2]` will output `float`.
143// Call `writeArrayDimensions` to write the type's accompanying array sizes.
144void MetalCodeGenerator::writeBaseType(const Type& type) {
145 switch (type.typeKind()) {
146 case Type::TypeKind::kStruct:
147 if (!this->writeStructDefinition(type)) {
148 this->write(type.name());
149 }
150 break;
151 case Type::TypeKind::kArray:
152 this->writeBaseType(type.componentType());
153 break;
154 default:
155 this->write(this->typeName(type));
156 break;
157 }
158}
159
160// Writes the array suffix of a type, if one exists. e.g. `float[2][4]` will output `[2][4]`.
161void MetalCodeGenerator::writeArrayDimensions(const Type& type) {
John Stilesc0c51062020-12-03 17:16:29 -0500162 if (type.isArray()) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500163 this->write("[");
164 if (type.columns() != Type::kUnsizedArray) {
165 this->write(to_string(type.columns()));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500166 }
John Stiles3dba3ee2020-12-02 23:35:49 -0500167 this->write("]");
168
169 this->writeArrayDimensions(type.componentType());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500170 }
171}
172
Ethan Nicholascc305772017-10-13 16:17:45 -0400173void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400174 switch (expr.kind()) {
175 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400176 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400177 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400178 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400179 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400180 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400181 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400182 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400183 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400184 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400185 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400186 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400187 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400188 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400189 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400190 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400191 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400192 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400193 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400194 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400195 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400197 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400198 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400199 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400200 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400201 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400202 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400203 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400204 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400205 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400206 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400207 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400208 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400209 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400210 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400211 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400212 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400213 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400214 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400215 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400216 break;
217 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500218#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400219 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500220#endif
221 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400222 }
223}
224
Timothy Liang6403b0e2018-05-17 10:40:04 -0400225void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400226 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400227 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400228 Intrinsic intrinsic = i->second;
229 int32_t intrinsicId = intrinsic.second;
230 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400231 case kSpecial_IntrinsicKind:
232 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400233 break;
234 case kMetal_IntrinsicKind:
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400235 this->writeExpression(*c.arguments()[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400236 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500237 case kEqual_MetalIntrinsic:
238 this->write(" == ");
239 break;
240 case kNotEqual_MetalIntrinsic:
241 this->write(" != ");
242 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400243 case kLessThan_MetalIntrinsic:
244 this->write(" < ");
245 break;
246 case kLessThanEqual_MetalIntrinsic:
247 this->write(" <= ");
248 break;
249 case kGreaterThan_MetalIntrinsic:
250 this->write(" > ");
251 break;
252 case kGreaterThanEqual_MetalIntrinsic:
253 this->write(" >= ");
254 break;
255 default:
256 ABORT("unsupported metal intrinsic kind");
257 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400258 this->writeExpression(*c.arguments()[1], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400259 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400260 default:
261 ABORT("unsupported intrinsic kind");
262 }
263}
264
Ethan Nicholascc305772017-10-13 16:17:45 -0400265void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400266 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400267 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400268 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400269 if (entry != fIntrinsicMap.end()) {
270 this->writeIntrinsicCall(c);
271 return;
272 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400273 const StringFragment& name = function.name();
Ethan Nicholased84b732020-10-08 11:45:44 -0400274 bool builtin = function.isBuiltin();
275 if (builtin && name == "atan" && arguments.size() == 2) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400276 this->write("atan2");
Ethan Nicholased84b732020-10-08 11:45:44 -0400277 } else if (builtin && name == "inversesqrt") {
Timothy Lianga06f2152018-05-24 15:33:31 -0400278 this->write("rsqrt");
Ethan Nicholased84b732020-10-08 11:45:44 -0400279 } else if (builtin && name == "inverse") {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400280 SkASSERT(arguments.size() == 1);
281 this->writeInverseHack(*arguments[0]);
John Stilesa80a3dc2020-10-20 10:24:56 -0400282 } else if (builtin && name == "frexp") {
283 // Our Metal codegen assumes that out params are pointers, but Metal's built-in frexp
284 // actually takes a reference for the exponent, not a pointer. We add in a helper function
285 // here to translate.
286 SkASSERT(arguments.size() == 2);
287 auto [iter, newlyCreated] = fHelpers.insert("frexp");
288 if (newlyCreated) {
289 fExtraFunctions.printf(
290 "float frexp(float arg, thread int* exp) { return frexp(arg, *exp); }\n");
291 }
292 this->write("frexp");
Ethan Nicholased84b732020-10-08 11:45:44 -0400293 } else if (builtin && name == "dFdx") {
Timothy Liang7d637782018-06-05 09:58:07 -0400294 this->write("dfdx");
Ethan Nicholased84b732020-10-08 11:45:44 -0400295 } else if (builtin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700296 // Flipping Y also negates the Y derivatives.
297 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400298 } else {
Ethan Nicholase2c49992020-10-05 11:49:11 -0400299 this->writeName(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400300 }
301 this->write("(");
302 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400303 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400304 this->write("_in");
305 separator = ", ";
306 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400307 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400308 this->write(separator);
309 this->write("_out");
310 separator = ", ";
311 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400312 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400313 this->write(separator);
314 this->write("_uniforms");
315 separator = ", ";
316 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400317 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400318 this->write(separator);
319 this->write("_globals");
320 separator = ", ";
321 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400322 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400323 this->write(separator);
324 this->write("_fragCoord");
325 separator = ", ";
326 }
Brian Osman5bf3e202020-10-13 10:34:18 -0400327 const std::vector<const Variable*>& parameters = function.parameters();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400328 for (size_t i = 0; i < arguments.size(); ++i) {
329 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400330 this->write(separator);
331 separator = ", ";
Ethan Nicholased84b732020-10-08 11:45:44 -0400332 if (parameters[i]->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400333 this->write("&");
334 }
335 this->writeExpression(arg, kSequence_Precedence);
336 }
337 this->write(")");
338}
339
Chris Daltondba7aab2018-11-15 10:57:49 -0500340void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400341 const Type& type = mat.type();
342 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500343 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400344 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500345 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
346 fWrittenIntrinsics.insert(name);
347 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500348 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500349 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
350 "}"
351 ).c_str());
352 }
353 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400354 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500355 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
356 fWrittenIntrinsics.insert(name);
357 fExtraFunctions.writeText((
358 typeName + " " + name + "(" + typeName + " m) {"
359 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
360 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
361 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
362 " float b01 = a22 * a11 - a12 * a21;"
363 " float b11 = -a22 * a10 + a12 * a20;"
364 " float b21 = a21 * a10 - a11 * a20;"
365 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
366 " return " + typeName +
367 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
368 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
369 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
370 " (1/det);"
371 "}"
372 ).c_str());
373 }
374 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400375 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500376 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
377 fWrittenIntrinsics.insert(name);
378 fExtraFunctions.writeText((
379 typeName + " " + name + "(" + typeName + " m) {"
380 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
381 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
382 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
383 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
384 " float b00 = a00 * a11 - a01 * a10;"
385 " float b01 = a00 * a12 - a02 * a10;"
386 " float b02 = a00 * a13 - a03 * a10;"
387 " float b03 = a01 * a12 - a02 * a11;"
388 " float b04 = a01 * a13 - a03 * a11;"
389 " float b05 = a02 * a13 - a03 * a12;"
390 " float b06 = a20 * a31 - a21 * a30;"
391 " float b07 = a20 * a32 - a22 * a30;"
392 " float b08 = a20 * a33 - a23 * a30;"
393 " float b09 = a21 * a32 - a22 * a31;"
394 " float b10 = a21 * a33 - a23 * a31;"
395 " float b11 = a22 * a33 - a23 * a32;"
396 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
397 " b04 * b07 + b05 * b06;"
398 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
399 " a02 * b10 - a01 * b11 - a03 * b09,"
400 " a31 * b05 - a32 * b04 + a33 * b03,"
401 " a22 * b04 - a21 * b05 - a23 * b03,"
402 " a12 * b08 - a10 * b11 - a13 * b07,"
403 " a00 * b11 - a02 * b08 + a03 * b07,"
404 " a32 * b02 - a30 * b05 - a33 * b01,"
405 " a20 * b05 - a22 * b02 + a23 * b01,"
406 " a10 * b10 - a11 * b08 + a13 * b06,"
407 " a01 * b08 - a00 * b10 - a03 * b06,"
408 " a30 * b04 - a31 * b02 + a33 * b00,"
409 " a21 * b02 - a20 * b04 - a23 * b00,"
410 " a11 * b07 - a10 * b09 - a12 * b06,"
411 " a00 * b09 - a01 * b07 + a02 * b06,"
412 " a31 * b01 - a30 * b03 - a32 * b00,"
413 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
414 "}"
415 ).c_str());
416 }
417 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500418 this->write(name);
419}
420
Timothy Liang6403b0e2018-05-17 10:40:04 -0400421void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400422 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400423 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400424 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400425 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400426 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400427 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400428 this->write(SAMPLER_SUFFIX);
429 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400430 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400431 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500432 // have to store the vector in a temp variable to avoid double evaluating it
433 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400434 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500435 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400436 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500437 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400438 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400439 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400440 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400441 this->write(")");
442 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400443 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400444 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500445 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400446 // 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 -0500447 String tmpX = "tmpX" + to_string(fVarCount++);
448 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400449 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400450 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500451 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400452 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500453 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400454 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500455 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400456 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500457 }
Brian Osman46787d52020-11-24 14:18:23 -0500458 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
459 case kDistance_SpecialIntrinsic: {
460 if (arguments[0]->type().columns() == 1) {
461 this->write("abs(");
462 this->writeExpression(*arguments[0], kAdditive_Precedence);
463 this->write(" - ");
464 this->writeExpression(*arguments[1], kAdditive_Precedence);
465 this->write(")");
466 } else {
467 this->write("distance(");
468 this->writeExpression(*arguments[0], kSequence_Precedence);
469 this->write(", ");
470 this->writeExpression(*arguments[1], kSequence_Precedence);
471 this->write(")");
472 }
473 break;
474 }
475 case kDot_SpecialIntrinsic: {
476 if (arguments[0]->type().columns() == 1) {
477 this->write("(");
478 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
479 this->write(" * ");
480 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
481 this->write(")");
482 } else {
483 this->write("dot(");
484 this->writeExpression(*arguments[0], kSequence_Precedence);
485 this->write(", ");
486 this->writeExpression(*arguments[1], kSequence_Precedence);
487 this->write(")");
488 }
489 break;
490 }
491 case kLength_SpecialIntrinsic: {
492 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
493 this->writeExpression(*arguments[0], kSequence_Precedence);
494 this->write(")");
495 break;
496 }
497 case kNormalize_SpecialIntrinsic: {
498 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
499 this->writeExpression(*arguments[0], kSequence_Precedence);
500 this->write(")");
501 break;
502 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400503 default:
504 ABORT("unsupported special intrinsic kind");
505 }
506}
507
John Stilesfcf8cb22020-08-06 14:29:22 -0400508// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
509// Cells that don't exist in the source matrix will be populated with identity-matrix values.
510void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
511 SkASSERT(rows <= 4);
512 SkASSERT(columns <= 4);
513
514 const char* columnSeparator = "";
515 for (int c = 0; c < columns; ++c) {
516 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
517 columnSeparator = "), ";
518
519 // Determine how many values to take from the source matrix for this row.
520 int swizzleLength = 0;
521 if (c < sourceMatrix.columns()) {
522 swizzleLength = std::min<>(rows, sourceMatrix.rows());
523 }
524
525 // Emit all the values from the source matrix row.
526 bool firstItem;
527 switch (swizzleLength) {
528 case 0: firstItem = true; break;
529 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
530 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
531 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
532 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
533 default: SkUNREACHABLE;
534 }
535
536 // Emit the placeholder identity-matrix cells.
537 for (int r = swizzleLength; r < rows; ++r) {
538 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
539 firstItem = false;
540 }
541 }
542
543 fExtraFunctions.writeText(")");
544}
545
546// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
547// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400548void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
549 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400550 size_t argIndex = 0;
551 int argPosition = 0;
552
553 const char* columnSeparator = "";
554 for (int c = 0; c < columns; ++c) {
555 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
556 columnSeparator = "), ";
557
558 const char* rowSeparator = "";
559 for (int r = 0; r < rows; ++r) {
560 fExtraFunctions.writeText(rowSeparator);
561 rowSeparator = ", ";
562
563 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400564 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400565 switch (argType.typeKind()) {
566 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400567 fExtraFunctions.printf("x%zu", argIndex);
568 break;
569 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400570 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400571 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
572 break;
573 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400574 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400575 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
576 argPosition / argType.rows(),
577 argPosition % argType.rows());
578 break;
579 }
580 default: {
581 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
582 fExtraFunctions.writeText("<error>");
583 break;
584 }
585 }
586
587 ++argPosition;
588 if (argPosition >= argType.columns() * argType.rows()) {
589 ++argIndex;
590 argPosition = 0;
591 }
592 } else {
593 SkDEBUGFAIL("not enough arguments for matrix constructor");
594 fExtraFunctions.writeText("<error>");
595 }
596 }
597 }
598
599 if (argPosition != 0 || argIndex != args.size()) {
600 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
601 fExtraFunctions.writeText(", <error>");
602 }
603
604 fExtraFunctions.writeText(")");
605}
606
John Stiles1bdafbf2020-05-28 12:17:20 -0400607// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
608// Keeps track of previously generated constructors so that we won't generate more than one
609// constructor for any given permutation of input argument types. Returns the name of the
610// generated constructor method.
611String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400612 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500613 int columns = matrix.columns();
614 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400615 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400616
617 // Create the helper-method name and use it as our lookup key.
618 String name;
619 name.appendf("float%dx%d_from", columns, rows);
620 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400621 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400622 }
623
624 // If a helper-method has already been synthesized, we don't need to synthesize it again.
625 auto [iter, newlyCreated] = fHelpers.insert(name);
626 if (!newlyCreated) {
627 return name;
628 }
629
630 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
631 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
632 // supply a mixture of scalars and vectors.)
633 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
634
635 size_t argIndex = 0;
636 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400637 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400638 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400639 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400640 argSeparator = ", ";
641 }
642
643 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
644
John Stiles9aeed132020-11-24 17:36:06 -0500645 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400646 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400647 } else {
648 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400649 }
650
John Stilesfcf8cb22020-08-06 14:29:22 -0400651 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500652 return name;
653}
654
655bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
656 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
657 return false;
658 }
659 if (t1.columns() > 1) {
660 return this->canCoerce(t1.componentType(), t2.componentType());
661 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500662 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500663}
664
John Stiles1bdafbf2020-05-28 12:17:20 -0400665bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
666 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500667 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400668 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500669 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400670
671 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
672 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
673 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
674 // scalars can be constructed trivially. In more complex cases, we generate a helper function
675 // that converts our inputs into a properly-shaped matrix.
676 // A matrix construct helper method is always used if any input argument is a matrix.
677 // Helper methods are also necessary when any argument would span multiple rows. For instance:
678 //
679 // float2 x = (1, 2);
680 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
681 // | 2 4 6 |
682 //
683 // float2 x = (2, 3);
684 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
685 // | 2 4 6 |
686 //
687 // float4 x = (1, 2, 3, 4);
688 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
689 // | 2 4 |
690 //
691
692 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400693 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400694 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500695 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400696 return true;
697 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400698 position += expr->type().columns();
699 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400700 // An input argument would span multiple rows; a helper function is required.
701 return true;
702 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400703 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400704 // We've advanced to the end of a row. Wrap to the start of the next row.
705 position = 0;
706 }
707 }
708
709 return false;
710}
711
712void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400713 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400714 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400715 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400716 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400717 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400718 const Type& argType = arg.type();
719 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400720 this->writeExpression(arg, parentPrecedence);
721 return;
722 }
723
724 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
725 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500726 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400727 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400728 this->write("float");
729 this->write(to_string(matrix.columns()));
730 this->write("x");
731 this->write(to_string(matrix.rows()));
732 this->write("(");
733 this->writeExpression(arg, parentPrecedence);
734 this->write(")");
735 return;
736 }
737 }
738
739 // Emit and invoke a matrix-constructor helper method if one is necessary.
740 if (this->matrixConstructHelperIsNeeded(c)) {
741 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000742 this->write("(");
743 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400744 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000745 this->write(separator);
746 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400747 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400748 }
John Stiles1fa15b12020-05-28 17:36:54 +0000749 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400750 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400751 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400752
753 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stiles3dba3ee2020-12-02 23:35:49 -0500754 this->writeBaseType(constructorType);
755 this->disallowArrayTypes(constructorType); // constructors of array types aren't valid exprs
John Stiles1bdafbf2020-05-28 12:17:20 -0400756 this->write("(");
757 const char* separator = "";
758 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400759 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400760 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400761 this->write(separator);
762 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -0500763 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400764 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400765 // Merge scalars and smaller vectors together.
766 if (!scalarCount) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500767 this->writeBaseType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400768 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400769 this->write("(");
770 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400771 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400772 }
773 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400774 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400775 this->write(")");
776 scalarCount = 0;
777 }
778 }
779 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400780}
781
782void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400783 if (fRTHeightName.length()) {
784 this->write("float4(_fragCoord.x, ");
785 this->write(fRTHeightName.c_str());
786 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500787 } else {
788 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
789 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400790}
791
792void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400793 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400794 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400795 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400796 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400797 case SK_FRAGCOORD_BUILTIN:
798 this->writeFragCoord();
799 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400800 case SK_VERTEXID_BUILTIN:
801 this->write("sk_VertexID");
802 break;
803 case SK_INSTANCEID_BUILTIN:
804 this->write("sk_InstanceID");
805 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400806 case SK_CLOCKWISE_BUILTIN:
807 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400808 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400809 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
810 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400811 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400812 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400813 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400814 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400815 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400816 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400817 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400818 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
819 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400820 this->write("_uniforms.");
821 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400822 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400823 }
824 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400825 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400826 }
827}
828
829void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400830 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400831 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400832 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400833 this->write("]");
834}
835
836void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400837 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
838 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
839 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400840 this->write(".");
841 }
Timothy Liang7d637782018-06-05 09:58:07 -0400842 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400843 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400844 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400845 break;
846 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400847 if (field->fName == "sk_PointSize") {
848 this->write("_out->sk_PointSize");
849 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400850 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400851 this->write("_globals->");
852 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
853 this->write("->");
854 }
Timothy Liang651286f2018-06-07 09:55:33 -0400855 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400856 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400857 }
858}
859
860void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400861 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400862 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400863 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -0400864 SkASSERT(c >= 0 && c <= 3);
865 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400866 }
867}
868
869MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
870 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400871 case Token::Kind::TK_STAR: // fall through
872 case Token::Kind::TK_SLASH: // fall through
873 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
874 case Token::Kind::TK_PLUS: // fall through
875 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
876 case Token::Kind::TK_SHL: // fall through
877 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
878 case Token::Kind::TK_LT: // fall through
879 case Token::Kind::TK_GT: // fall through
880 case Token::Kind::TK_LTEQ: // fall through
881 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
882 case Token::Kind::TK_EQEQ: // fall through
883 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
884 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
885 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
886 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
887 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
888 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
889 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
890 case Token::Kind::TK_EQ: // fall through
891 case Token::Kind::TK_PLUSEQ: // fall through
892 case Token::Kind::TK_MINUSEQ: // fall through
893 case Token::Kind::TK_STAREQ: // fall through
894 case Token::Kind::TK_SLASHEQ: // fall through
895 case Token::Kind::TK_PERCENTEQ: // fall through
896 case Token::Kind::TK_SHLEQ: // fall through
897 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400898 case Token::Kind::TK_BITWISEANDEQ: // fall through
899 case Token::Kind::TK_BITWISEXOREQ: // fall through
900 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
901 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400902 default: ABORT("unsupported binary operator");
903 }
904}
905
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500906void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
907 const Type& result) {
908 String key = "TimesEqual" + left.name() + right.name();
909 if (fHelpers.find(key) == fHelpers.end()) {
910 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
911 " left = left * right;\n"
912 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400913 "}", String(result.name()).c_str(), String(left.name()).c_str(),
914 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500915 }
916}
917
Ethan Nicholascc305772017-10-13 16:17:45 -0400918void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
919 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -0400920 const Expression& left = *b.left();
921 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400922 const Type& leftType = left.type();
923 const Type& rightType = right.type();
924 Token::Kind op = b.getOperator();
925 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500926 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400927 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400928 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500929 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500930 this->write("all");
931 needParens = true;
932 }
933 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400934 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500935 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400936 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500937 needParens = true;
938 }
939 break;
940 default:
941 break;
942 }
943 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400944 this->write("(");
945 }
Brian Osman79457ef2020-09-24 15:01:27 -0400946 if (Compiler::IsAssignment(op) && left.is<VariableReference>() &&
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400947 left.as<VariableReference>().variable()->storage() == Variable::Storage::kParameter &&
Ethan Nicholas78686922020-10-08 06:46:27 -0400948 left.as<VariableReference>().variable()->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400949 // writing to an out parameter. Since we have to turn those into pointers, we have to
950 // dereference it here.
951 this->write("*");
952 }
John Stiles9aeed132020-11-24 17:36:06 -0500953 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400954 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500955 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400956 this->writeExpression(left, precedence);
957 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
958 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400959 // This doesn't compile in Metal:
960 // float4 x = float4(1);
961 // x.xy *= float2x2(...);
962 // with the error message "non-const reference cannot bind to vector element",
963 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
964 // as long as the LHS has no side effects, and hope for the best otherwise.
965 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400966 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400967 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -0500968 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400969 SkASSERT(opName.endsWith("="));
970 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400971 this->write(" ");
972 } else {
John Stilesd6449e92020-11-30 09:13:23 -0500973 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400974 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400975 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500976 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400977 this->write(")");
978 }
979}
980
981void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
982 Precedence parentPrecedence) {
983 if (kTernary_Precedence >= parentPrecedence) {
984 this->write("(");
985 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400986 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400987 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400988 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400989 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400990 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400991 if (kTernary_Precedence >= parentPrecedence) {
992 this->write(")");
993 }
994}
995
996void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
997 Precedence parentPrecedence) {
998 if (kPrefix_Precedence >= parentPrecedence) {
999 this->write("(");
1000 }
John Stilesd6449e92020-11-30 09:13:23 -05001001 this->write(OperatorName(p.getOperator()));
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001002 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001003 if (kPrefix_Precedence >= parentPrecedence) {
1004 this->write(")");
1005 }
1006}
1007
1008void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1009 Precedence parentPrecedence) {
1010 if (kPostfix_Precedence >= parentPrecedence) {
1011 this->write("(");
1012 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001013 this->writeExpression(*p.operand(), kPostfix_Precedence);
John Stilesd6449e92020-11-30 09:13:23 -05001014 this->write(OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001015 if (kPostfix_Precedence >= parentPrecedence) {
1016 this->write(")");
1017 }
1018}
1019
1020void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001021 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001022}
1023
1024void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001025 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001026 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001027 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001028 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001029 }
1030}
1031
1032void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001033 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001034}
1035
1036void MetalCodeGenerator::writeSetting(const Setting& s) {
1037 ABORT("internal error; setting was not folded to a constant during compilation\n");
1038}
1039
John Stiles569249b2020-11-03 12:18:22 -05001040bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001041 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001042 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001043 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001044 switch (fProgram.fKind) {
1045 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001046 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001047 break;
1048 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001049 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001050 break;
1051 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001052 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001053 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001054 }
1055 this->write("(Inputs _in [[stage_in]]");
1056 if (-1 != fUniformBuffer) {
1057 this->write(", constant Uniforms& _uniforms [[buffer(" +
1058 to_string(fUniformBuffer) + ")]]");
1059 }
Brian Osman133724c2020-10-28 14:14:39 -04001060 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001061 if (e->is<GlobalVarDeclaration>()) {
1062 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001063 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1064 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1065 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001066 fErrors.error(decls.fOffset,
1067 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001068 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001069 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001070 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001071 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001072 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001073 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001074 }
1075 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001076 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001077 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001078 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001079 this->write(")]]");
1080 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001081 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001082 this->write(SAMPLER_SUFFIX);
1083 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001084 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001085 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001086 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001087 } else if (e->is<InterfaceBlock>()) {
1088 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001089 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001090 continue;
1091 }
John Stilesbc3c41b2020-12-04 10:52:40 -05001092 if (intf.variable().modifiers().fLayout.fBinding < 0) {
1093 fErrors.error(intf.fOffset,
1094 "Metal interface blocks must have 'layout(binding=...)'");
1095 return false;
1096 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001097 this->write(", constant ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001098 this->writeBaseType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001099 this->write("& " );
1100 this->write(fInterfaceBlockNameMap[&intf]);
1101 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001102 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001103 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001104 }
1105 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001106 if (fProgram.fKind == Program::kFragment_Kind) {
1107 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001108 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001109 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001110 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001111 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001112 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001113 } else if (fProgram.fKind == Program::kVertex_Kind) {
1114 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001115 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001116 separator = ", ";
1117 } else {
John Stiles3dba3ee2020-12-02 23:35:49 -05001118 this->writeBaseType(f.returnType());
1119 this->disallowArrayTypes(f.returnType()); // return types can't be arrays in SkSL/GLSL
Timothy Liang651286f2018-06-07 09:55:33 -04001120 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001121 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001122 this->write("(");
John Stiles569249b2020-11-03 12:18:22 -05001123 Requirements requirements = this->requirements(f);
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001124 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001125 this->write("Inputs _in");
1126 separator = ", ";
1127 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001128 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001129 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001130 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001131 separator = ", ";
1132 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001133 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001134 this->write(separator);
1135 this->write("Uniforms _uniforms");
1136 separator = ", ";
1137 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001138 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001139 this->write(separator);
1140 this->write("thread Globals* _globals");
1141 separator = ", ";
1142 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001143 if (requirements & kFragCoord_Requirement) {
1144 this->write(separator);
1145 this->write("float4 _fragCoord");
1146 separator = ", ";
1147 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001148 }
John Stiles569249b2020-11-03 12:18:22 -05001149 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001150 this->write(separator);
1151 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001152 this->writeModifiers(param->modifiers(), false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001153 const Type* type = &param->type();
John Stiles3dba3ee2020-12-02 23:35:49 -05001154 this->writeBaseType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001155 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001156 this->write("*");
1157 }
Timothy Liang651286f2018-06-07 09:55:33 -04001158 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001159 this->writeName(param->name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001160 this->writeArrayDimensions(*type);
Ethan Nicholascc305772017-10-13 16:17:45 -04001161 }
John Stiles569249b2020-11-03 12:18:22 -05001162 this->write(")");
1163 return true;
1164}
Ethan Nicholascc305772017-10-13 16:17:45 -04001165
John Stiles569249b2020-11-03 12:18:22 -05001166void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1167 this->writeFunctionDeclaration(f.declaration());
1168 this->writeLine(";");
1169}
1170
John Stiles986c7fb2020-12-01 14:44:56 -05001171static bool is_block_ending_with_return(const Statement* stmt) {
1172 // This function detects (potentially nested) blocks that end in a return statement.
1173 if (!stmt->is<Block>()) {
1174 return false;
1175 }
1176 const StatementArray& block = stmt->as<Block>().children();
1177 for (int index = block.count(); index--; ) {
1178 const Statement& stmt = *block[index];
1179 if (stmt.is<ReturnStatement>()) {
1180 return true;
1181 }
1182 if (stmt.is<Block>()) {
1183 return is_block_ending_with_return(&stmt);
1184 }
1185 if (!stmt.is<Nop>()) {
1186 break;
1187 }
1188 }
1189 return false;
1190}
1191
John Stiles569249b2020-11-03 12:18:22 -05001192void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001193 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001194
John Stiles569249b2020-11-03 12:18:22 -05001195 if (!this->writeFunctionDeclaration(f.declaration())) {
1196 return;
1197 }
1198
John Stiles986c7fb2020-12-01 14:44:56 -05001199 fCurrentFunction = &f.declaration();
1200 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1201
John Stiles569249b2020-11-03 12:18:22 -05001202 this->writeLine(" {");
1203
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001204 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001205 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001206 this->writeLine(" Outputs _outputStruct;");
1207 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001208 }
John Stilesc67b3622020-05-28 17:53:13 -04001209
Ethan Nicholascc305772017-10-13 16:17:45 -04001210 fFunctionHeader = "";
1211 OutputStream* oldOut = fOut;
1212 StringStream buffer;
1213 fOut = &buffer;
1214 fIndentation++;
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001215 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001216 if (!stmt->isEmpty()) {
1217 this->writeStatement(*stmt);
1218 this->writeLine();
1219 }
1220 }
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001221 if (f.declaration().name() == "main") {
John Stiles986c7fb2020-12-01 14:44:56 -05001222 // If the main function doesn't end with a return, we need to synthesize one here.
1223 if (!is_block_ending_with_return(f.body().get())) {
1224 this->writeReturnStatementFromMain();
1225 this->writeLine("");
Ethan Nicholascc305772017-10-13 16:17:45 -04001226 }
1227 }
1228 fIndentation--;
1229 this->writeLine("}");
1230
1231 fOut = oldOut;
1232 this->write(fFunctionHeader);
1233 this->write(buffer.str());
1234}
1235
1236void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1237 bool globalContext) {
1238 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1239 this->write("thread ");
1240 }
1241 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001242 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001243 }
1244}
1245
1246void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001247 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001248 return;
1249 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001250 this->writeModifiers(intf.variable().modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001251 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001252 this->writeLine(intf.typeName() + " {");
1253 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001254 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001255 structType = &structType->componentType();
1256 }
John Stiles3dba3ee2020-12-02 23:35:49 -05001257 fWrittenStructs.push_back(structType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001258 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001259 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001260 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001261 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001262 }
1263 fIndentation--;
1264 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001265 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001266 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001267 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001268 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001269 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001270 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001271 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001272 } else if (intf.arraySize() == Type::kUnsizedArray){
1273 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001274 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001275 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001276 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001277 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001278 }
1279 this->writeLine(";");
1280}
1281
Timothy Liangdc89f192018-06-13 09:20:31 -04001282void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1283 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001284 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001285 int currentOffset = 0;
1286 for (const auto& field: fields) {
1287 int fieldOffset = field.fModifiers.fLayout.fOffset;
1288 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001289 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001290 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1291 return;
1292 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001293 if (fieldOffset != -1) {
1294 if (currentOffset > fieldOffset) {
1295 fErrors.error(parentOffset,
1296 "offset of field '" + field.fName + "' must be at least " +
1297 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001298 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001299 } else if (currentOffset < fieldOffset) {
1300 this->write("char pad");
1301 this->write(to_string(fPaddingCount++));
1302 this->write("[");
1303 this->write(to_string(fieldOffset - currentOffset));
1304 this->writeLine("];");
1305 currentOffset = fieldOffset;
1306 }
1307 int alignment = memoryLayout.alignment(*fieldType);
1308 if (fieldOffset % alignment) {
1309 fErrors.error(parentOffset,
1310 "offset of field '" + field.fName + "' must be a multiple of " +
1311 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001312 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001313 }
1314 }
Brian Osman8609a242020-09-08 14:01:49 -04001315 size_t fieldSize = memoryLayout.size(*fieldType);
1316 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1317 fErrors.error(parentOffset, "field offset overflow");
1318 return;
1319 }
1320 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001321 this->writeModifiers(field.fModifiers, false);
John Stiles3dba3ee2020-12-02 23:35:49 -05001322 this->writeBaseType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001323 this->write(" ");
1324 this->writeName(field.fName);
John Stiles3dba3ee2020-12-02 23:35:49 -05001325 this->writeArrayDimensions(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001326 this->writeLine(";");
1327 if (parentIntf) {
1328 fInterfaceBlockMap[&field] = parentIntf;
1329 }
1330 }
1331}
1332
Ethan Nicholascc305772017-10-13 16:17:45 -04001333void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1334 this->writeExpression(value, kTopLevel_Precedence);
1335}
1336
Timothy Liang651286f2018-06-07 09:55:33 -04001337void MetalCodeGenerator::writeName(const String& name) {
1338 if (fReservedWords.find(name) != fReservedWords.end()) {
1339 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1340 }
1341 this->write(name);
1342}
1343
Brian Osmanc0213602020-10-06 14:43:32 -04001344void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001345 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001346 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001347 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001348 this->writeModifiers(var.var().modifiers(), global);
John Stiles3dba3ee2020-12-02 23:35:49 -05001349 this->writeBaseType(var.baseType());
1350 this->disallowArrayTypes(var.baseType()); // `float[2] x` shouldn't be possible (invalid SkSL)
Brian Osmanc0213602020-10-06 14:43:32 -04001351 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001352 this->writeName(var.var().name());
John Stiles62a56462020-12-03 10:41:58 -05001353 if (var.arraySize() > 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001354 this->write("[");
John Stiles62a56462020-12-03 10:41:58 -05001355 this->write(to_string(var.arraySize()));
Brian Osmanc0213602020-10-06 14:43:32 -04001356 this->write("]");
John Stiles62a56462020-12-03 10:41:58 -05001357 } else if (var.arraySize() == Type::kUnsizedArray){
1358 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001359 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001360 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001361 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001362 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001363 }
1364 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001365}
1366
1367void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001368 switch (s.kind()) {
1369 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001370 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001371 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001372 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001373 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001374 this->write(";");
1375 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001376 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001377 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001378 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001379 case Statement::Kind::kVarDeclaration:
1380 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001381 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001382 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001383 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001384 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001385 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001386 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001387 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001388 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001389 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001390 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001391 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001392 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001393 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001394 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001395 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001396 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001397 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001398 this->write("break;");
1399 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001400 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001401 this->write("continue;");
1402 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001403 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001404 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001405 break;
John Stiles98c1f822020-09-09 14:18:53 -04001406 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001407 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001408 this->write(";");
1409 break;
1410 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001411#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001412 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001413#endif
1414 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001415 }
1416}
1417
Ethan Nicholascc305772017-10-13 16:17:45 -04001418void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001419 bool isScope = b.isScope();
1420 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001421 this->writeLine("{");
1422 fIndentation++;
1423 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001424 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1425 if (!stmt->isEmpty()) {
1426 this->writeStatement(*stmt);
1427 this->writeLine();
1428 }
1429 }
1430 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001431 fIndentation--;
1432 this->write("}");
1433 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001434}
1435
1436void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1437 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001438 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001440 this->writeStatement(*stmt.ifTrue());
1441 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001442 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001443 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001444 }
1445}
1446
1447void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1448 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001449 if (f.initializer() && !f.initializer()->isEmpty()) {
1450 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001451 } else {
1452 this->write("; ");
1453 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001454 if (f.test()) {
1455 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001456 }
1457 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001458 if (f.next()) {
1459 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001460 }
1461 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001462 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001463}
1464
1465void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1466 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001467 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001468 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001469 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001470}
1471
1472void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1473 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001474 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001475 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001476 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001477 this->write(");");
1478}
1479
1480void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1481 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001482 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001483 this->writeLine(") {");
1484 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001485 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1486 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001487 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001488 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001489 this->writeLine(":");
1490 } else {
1491 this->writeLine("default:");
1492 }
1493 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001494 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001495 this->writeStatement(*stmt);
1496 this->writeLine();
1497 }
1498 fIndentation--;
1499 }
1500 fIndentation--;
1501 this->write("}");
1502}
1503
John Stiles986c7fb2020-12-01 14:44:56 -05001504void MetalCodeGenerator::writeReturnStatementFromMain() {
1505 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
1506 switch (fProgram.fKind) {
1507 case Program::kFragment_Kind:
1508 this->write("return *_out;");
1509 break;
1510 case Program::kVertex_Kind:
1511 this->write("return (_out->sk_Position.y = -_out->sk_Position.y, *_out);");
1512 break;
1513 default:
1514 SkDEBUGFAIL("unsupported kind of program");
1515 }
1516}
1517
Ethan Nicholascc305772017-10-13 16:17:45 -04001518void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stiles986c7fb2020-12-01 14:44:56 -05001519 if (fCurrentFunction && fCurrentFunction->name() == "main") {
1520 if (r.expression()) {
1521 fErrors.error(r.fOffset, "Metal does not support returning values from main()");
1522 }
1523 this->writeReturnStatementFromMain();
1524 return;
1525 }
1526
Ethan Nicholascc305772017-10-13 16:17:45 -04001527 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001528 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001529 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001530 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001531 }
1532 this->write(";");
1533}
1534
1535void MetalCodeGenerator::writeHeader() {
1536 this->write("#include <metal_stdlib>\n");
1537 this->write("#include <simd/simd.h>\n");
1538 this->write("using namespace metal;\n");
1539}
1540
1541void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001542 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001543 if (e->is<GlobalVarDeclaration>()) {
1544 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001545 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001546 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001547 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001548 if (-1 == fUniformBuffer) {
1549 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001550 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001551 if (-1 == fUniformBuffer) {
1552 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1553 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001554 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001555 if (-1 == fUniformBuffer) {
1556 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1557 "the same 'layout(set=...)'");
1558 }
1559 }
1560 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001561 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001562 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001563 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001564 this->writeArrayDimensions(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001565 this->write(";\n");
1566 }
1567 }
1568 }
1569 if (-1 != fUniformBuffer) {
1570 this->write("};\n");
1571 }
1572}
1573
1574void MetalCodeGenerator::writeInputStruct() {
1575 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001576 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001577 if (e->is<GlobalVarDeclaration>()) {
1578 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001579 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001580 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1581 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001582 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001583 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001584 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001585 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001586 this->writeArrayDimensions(var.type());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001587 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001588 if (fProgram.fKind == Program::kVertex_Kind) {
1589 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001590 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001591 } else if (fProgram.fKind == Program::kFragment_Kind) {
1592 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001593 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001594 }
1595 }
1596 this->write(";\n");
1597 }
1598 }
1599 }
1600 this->write("};\n");
1601}
1602
1603void MetalCodeGenerator::writeOutputStruct() {
1604 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001605 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001606 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001607 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001608 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001609 }
Brian Osman133724c2020-10-28 14:14:39 -04001610 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001611 if (e->is<GlobalVarDeclaration>()) {
1612 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001613 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001614 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1615 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001616 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001617 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001618 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001619 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001620 this->writeArrayDimensions(var.type());
John Stiles842b3592020-12-01 10:36:37 -05001621
1622 int location = var.modifiers().fLayout.fLocation;
1623 if (location < 0) {
1624 fErrors.error(var.fOffset,
1625 "Metal out variables must have 'layout(location=...)'");
1626 } else if (fProgram.fKind == Program::kVertex_Kind) {
1627 this->write(" [[user(locn" + to_string(location) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001628 } else if (fProgram.fKind == Program::kFragment_Kind) {
John Stiles842b3592020-12-01 10:36:37 -05001629 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001630 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001631 if (colorIndex) {
1632 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001633 }
Brian Osmanc0213602020-10-06 14:43:32 -04001634 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001635 }
1636 this->write(";\n");
1637 }
1638 }
Timothy Liang7d637782018-06-05 09:58:07 -04001639 }
1640 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001641 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001642 }
1643 this->write("};\n");
1644}
1645
1646void MetalCodeGenerator::writeInterfaceBlocks() {
1647 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001648 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001649 if (e->is<InterfaceBlock>()) {
1650 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001651 wroteInterfaceBlock = true;
1652 }
1653 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001654 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001655 this->writeLine("struct sksl_synthetic_uniforms {");
1656 this->writeLine(" float u_skRTHeight;");
1657 this->writeLine("};");
1658 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001659}
1660
John Stilesdc75a972020-11-25 16:24:55 -05001661void MetalCodeGenerator::writeStructDefinitions() {
1662 for (const ProgramElement* e : fProgram.elements()) {
1663 if (e->is<StructDefinition>()) {
1664 if (this->writeStructDefinition(e->as<StructDefinition>().type())) {
1665 this->writeLine(";");
1666 }
1667 } else if (e->is<GlobalVarDeclaration>()) {
1668 // If a global var declaration introduces a struct type, we need to write that type
1669 // here, since globals are all embedded in a sub-struct.
1670 const Type* type = &e->as<GlobalVarDeclaration>().declaration()
1671 ->as<VarDeclaration>().baseType();
John Stilesc0c51062020-12-03 17:16:29 -05001672 if (type->isStruct()) {
John Stilesdc75a972020-11-25 16:24:55 -05001673 if (this->writeStructDefinition(*type)) {
1674 this->writeLine(";");
1675 }
1676 }
1677 }
1678 }
1679}
1680
John Stilescdcdb042020-07-06 09:03:51 -04001681void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1682 // Visit the interface blocks.
1683 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05001684 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04001685 }
Brian Osman133724c2020-10-28 14:14:39 -04001686 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001687 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001688 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001689 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001690 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1691 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1692 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001693 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001694 var.type().typeKind() == Type::TypeKind::kSampler) {
1695 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1696 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001697 visitor->visitTexture(var.type(), var.name());
1698 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04001699 } else {
1700 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001701 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001702 }
1703 }
1704 }
John Stilescdcdb042020-07-06 09:03:51 -04001705}
1706
1707void MetalCodeGenerator::writeGlobalStruct() {
1708 class : public GlobalStructVisitor {
1709 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001710 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stilescdcdb042020-07-06 09:03:51 -04001711 this->AddElement();
1712 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001713 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001714 fCodeGen->write("* ");
1715 fCodeGen->writeName(blockName);
1716 fCodeGen->write(";\n");
1717 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001718 void visitTexture(const Type& type, const String& name) override {
John Stilescdcdb042020-07-06 09:03:51 -04001719 this->AddElement();
1720 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001721 fCodeGen->writeBaseType(type);
John Stilescdcdb042020-07-06 09:03:51 -04001722 fCodeGen->write(" ");
1723 fCodeGen->writeName(name);
John Stiles3dba3ee2020-12-02 23:35:49 -05001724 fCodeGen->writeArrayDimensions(type);
John Stilescdcdb042020-07-06 09:03:51 -04001725 fCodeGen->write(";\n");
1726 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001727 void visitSampler(const Type&, const String& name) override {
John Stilescdcdb042020-07-06 09:03:51 -04001728 this->AddElement();
1729 fCodeGen->write(" sampler ");
1730 fCodeGen->writeName(name);
1731 fCodeGen->write(";\n");
1732 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001733 void visitVariable(const Variable& var, const Expression* value) override {
John Stilescdcdb042020-07-06 09:03:51 -04001734 this->AddElement();
1735 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001736 fCodeGen->writeBaseType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001737 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001738 fCodeGen->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001739 fCodeGen->writeArrayDimensions(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001740 fCodeGen->write(";\n");
1741 }
1742 void AddElement() {
1743 if (fFirst) {
1744 fCodeGen->write("struct Globals {\n");
1745 fFirst = false;
1746 }
1747 }
1748 void Finish() {
1749 if (!fFirst) {
1750 fCodeGen->write("};");
1751 fFirst = true;
1752 }
1753 }
1754
1755 MetalCodeGenerator* fCodeGen = nullptr;
1756 bool fFirst = true;
1757 } visitor;
1758
1759 visitor.fCodeGen = this;
1760 this->visitGlobalStruct(&visitor);
1761 visitor.Finish();
1762}
1763
1764void MetalCodeGenerator::writeGlobalInit() {
1765 class : public GlobalStructVisitor {
1766 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001767 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04001768 const String& blockName) override {
1769 this->AddElement();
1770 fCodeGen->write("&");
1771 fCodeGen->writeName(blockName);
1772 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001773 void visitTexture(const Type&, const String& name) override {
John Stilescdcdb042020-07-06 09:03:51 -04001774 this->AddElement();
1775 fCodeGen->writeName(name);
1776 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001777 void visitSampler(const Type&, const String& name) override {
John Stilescdcdb042020-07-06 09:03:51 -04001778 this->AddElement();
1779 fCodeGen->writeName(name);
1780 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001781 void visitVariable(const Variable& var, const Expression* value) override {
John Stilescdcdb042020-07-06 09:03:51 -04001782 this->AddElement();
1783 if (value) {
1784 fCodeGen->writeVarInitializer(var, *value);
1785 } else {
1786 fCodeGen->write("{}");
1787 }
1788 }
1789 void AddElement() {
1790 if (fFirst) {
1791 fCodeGen->write(" Globals globalStruct{");
1792 fFirst = false;
1793 } else {
1794 fCodeGen->write(", ");
1795 }
1796 }
1797 void Finish() {
1798 if (!fFirst) {
1799 fCodeGen->writeLine("};");
1800 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1801 fCodeGen->writeLine(" (void)_globals;");
1802 }
1803 }
1804 MetalCodeGenerator* fCodeGen = nullptr;
1805 bool fFirst = true;
1806 } visitor;
1807
1808 visitor.fCodeGen = this;
1809 this->visitGlobalStruct(&visitor);
1810 visitor.Finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001811}
1812
Ethan Nicholascc305772017-10-13 16:17:45 -04001813void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001814 switch (e.kind()) {
1815 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001816 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001817 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001818 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1819 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1820 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001821 if (-1 == builtin) {
1822 // normal var
1823 this->writeVarDeclaration(decl, true);
1824 this->writeLine();
1825 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1826 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001827 }
1828 break;
1829 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001830 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001831 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001832 break;
John Stilesdc75a972020-11-25 16:24:55 -05001833 case ProgramElement::Kind::kStructDefinition:
1834 // Handled in writeStructDefinitions. Do nothing.
1835 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001836 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001837 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001838 break;
John Stiles569249b2020-11-03 12:18:22 -05001839 case ProgramElement::Kind::kFunctionPrototype:
1840 this->writeFunctionPrototype(e.as<FunctionPrototype>());
1841 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001842 case ProgramElement::Kind::kModifiers:
Ethan Nicholas077050b2020-10-13 10:30:20 -04001843 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(), true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001844 this->writeLine(";");
1845 break;
John Stiles712fd6b2020-11-25 22:25:43 -05001846 case ProgramElement::Kind::kEnum:
1847 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001849#ifdef SK_DEBUG
1850 ABORT("unsupported program element: %s\n", e.description().c_str());
1851#endif
1852 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001853 }
1854}
1855
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001856MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1857 if (!e) {
1858 return kNo_Requirements;
1859 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001860 switch (e->kind()) {
1861 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001862 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001863 Requirements result = this->requirements(f.function());
1864 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001865 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001866 }
1867 return result;
1868 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001869 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001870 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001871 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001872 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001873 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001874 }
1875 return result;
1876 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001877 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001878 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001879 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001880 return kGlobals_Requirement;
1881 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001882 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001883 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001884 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001885 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001886 case Expression::Kind::kBinary: {
1887 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001888 return this->requirements(bin.left().get()) |
1889 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001890 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001891 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001892 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001893 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001894 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001895 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001896 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001897 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001898 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001899 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001900 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001901 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1902 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001903 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001904 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001905 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001906 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001907 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001908 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001909 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001910 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001911 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001912 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001913 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001914 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001915 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001916 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001917 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001918 } else {
1919 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001920 }
1921 }
1922 return result;
1923 }
1924 default:
1925 return kNo_Requirements;
1926 }
1927}
1928
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001929MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1930 if (!s) {
1931 return kNo_Requirements;
1932 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001933 switch (s->kind()) {
1934 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001935 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001936 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001937 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001938 }
1939 return result;
1940 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001941 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001942 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001943 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001944 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001945 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001946 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001947 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001948 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001949 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001950 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001951 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001952 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001953 return this->requirements(i.test().get()) |
1954 this->requirements(i.ifTrue().get()) |
1955 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001956 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001957 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001958 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001959 return this->requirements(f.initializer().get()) |
1960 this->requirements(f.test().get()) |
1961 this->requirements(f.next().get()) |
1962 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001963 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001964 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001965 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001966 return this->requirements(w.test().get()) |
1967 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001968 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001969 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001970 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001971 return this->requirements(d.test().get()) |
1972 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001973 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001974 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001975 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001976 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04001977 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
1978 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001979 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001980 }
1981 }
1982 return result;
1983 }
1984 default:
1985 return kNo_Requirements;
1986 }
1987}
1988
1989MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001990 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001991 return kNo_Requirements;
1992 }
1993 auto found = fRequirements.find(&f);
1994 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001995 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04001996 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001997 if (e->is<FunctionDefinition>()) {
1998 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001999 if (&def.declaration() == &f) {
2000 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002001 fRequirements[&f] = reqs;
2002 return reqs;
2003 }
2004 }
2005 }
John Stiles569249b2020-11-03 12:18:22 -05002006 // We never found a definition for this declared function, but it's legal to prototype a
2007 // function without ever giving a definition, as long as you don't call it.
2008 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002009 }
2010 return found->second;
2011}
2012
Timothy Liangb8eeb802018-07-23 16:46:16 -04002013bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04002014 OutputStream* rawOut = fOut;
2015 fOut = &fHeader;
2016 fProgramKind = fProgram.fKind;
2017 this->writeHeader();
John Stilesdc75a972020-11-25 16:24:55 -05002018 this->writeStructDefinitions();
Ethan Nicholascc305772017-10-13 16:17:45 -04002019 this->writeUniformStruct();
2020 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04002021 this->writeOutputStruct();
2022 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04002023 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04002024 StringStream body;
2025 fOut = &body;
Brian Osman133724c2020-10-28 14:14:39 -04002026 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002027 this->writeProgramElement(*e);
Ethan Nicholascc305772017-10-13 16:17:45 -04002028 }
2029 fOut = rawOut;
2030
2031 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05002032 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04002033 write_stringstream(body, *rawOut);
Brian Osman8609a242020-09-08 14:01:49 -04002034 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002035}
2036
John Stilesa6841be2020-08-06 14:11:56 -04002037} // namespace SkSL