blob: 7b17b220be6bab029f64eaebbfc0ceac7aa340d4 [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:
John Stiles47b4b192020-12-08 18:08:11 -0500235 this->write("(");
236 this->writeExpression(*c.arguments()[0], kRelational_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400237 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500238 case kEqual_MetalIntrinsic:
239 this->write(" == ");
240 break;
241 case kNotEqual_MetalIntrinsic:
242 this->write(" != ");
243 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400244 case kLessThan_MetalIntrinsic:
245 this->write(" < ");
246 break;
247 case kLessThanEqual_MetalIntrinsic:
248 this->write(" <= ");
249 break;
250 case kGreaterThan_MetalIntrinsic:
251 this->write(" > ");
252 break;
253 case kGreaterThanEqual_MetalIntrinsic:
254 this->write(" >= ");
255 break;
256 default:
John Stiles47b4b192020-12-08 18:08:11 -0500257 ABORT("unsupported Metal intrinsic kind");
Timothy Lianga06f2152018-05-24 15:33:31 -0400258 }
John Stiles47b4b192020-12-08 18:08:11 -0500259 this->writeExpression(*c.arguments()[1], kRelational_Precedence);
260 this->write(")");
Timothy Lianga06f2152018-05-24 15:33:31 -0400261 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400262 default:
263 ABORT("unsupported intrinsic kind");
264 }
265}
266
John Stilesb21fac22020-12-04 15:36:49 -0500267String MetalCodeGenerator::getOutParamHelper(const FunctionDeclaration& function,
268 const ExpressionArray& arguments) {
269 // TODO: actually synthesize helper method.
270 return String::printf("/*needs swizzle fix*/ %s", String(function.name()).c_str());
271}
272
Ethan Nicholascc305772017-10-13 16:17:45 -0400273void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400274 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400275 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400276 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400277 if (entry != fIntrinsicMap.end()) {
278 this->writeIntrinsicCall(c);
279 return;
280 }
John Stilesb21fac22020-12-04 15:36:49 -0500281 String name = function.name();
Ethan Nicholased84b732020-10-08 11:45:44 -0400282 bool builtin = function.isBuiltin();
John Stilesb21fac22020-12-04 15:36:49 -0500283
Ethan Nicholased84b732020-10-08 11:45:44 -0400284 if (builtin && name == "atan" && arguments.size() == 2) {
John Stilesb21fac22020-12-04 15:36:49 -0500285 name = "atan2";
Ethan Nicholased84b732020-10-08 11:45:44 -0400286 } else if (builtin && name == "inversesqrt") {
John Stilesb21fac22020-12-04 15:36:49 -0500287 name = "rsqrt";
Ethan Nicholased84b732020-10-08 11:45:44 -0400288 } else if (builtin && name == "inverse") {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400289 SkASSERT(arguments.size() == 1);
John Stilesb21fac22020-12-04 15:36:49 -0500290 name = this->getInverseHack(*arguments[0]);
Ethan Nicholased84b732020-10-08 11:45:44 -0400291 } else if (builtin && name == "dFdx") {
John Stilesb21fac22020-12-04 15:36:49 -0500292 name = "dfdx";
Ethan Nicholased84b732020-10-08 11:45:44 -0400293 } else if (builtin && name == "dFdy") {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700294 // Flipping Y also negates the Y derivatives.
John Stilesb21fac22020-12-04 15:36:49 -0500295 if (fProgram.fSettings.fFlipY) {
296 this->write("-");
297 }
298 name = "dfdy";
Ethan Nicholascc305772017-10-13 16:17:45 -0400299 }
John Stilesb21fac22020-12-04 15:36:49 -0500300
301 // GLSL supports passing swizzled variables to out params; Metal doesn't. To emulate that
302 // support, we synthesize a helper function which performs the swizzle into a temporary
303 // variable, calls the original function, then writes the temp var back into the out param.
304 const std::vector<const Variable*>& parameters = function.parameters();
305 SkASSERT(arguments.size() == parameters.size());
306 for (size_t index = 0; index < arguments.size(); ++index) {
307 // If this is an out parameter...
308 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
309 // Inspect the expression to see if it contains a swizzle.
310 Analysis::AssignmentInfo info;
311 bool outParamIsAssignable = Analysis::IsAssignable(*arguments[index], &info, nullptr);
312 SkASSERT(outParamIsAssignable); // assignability was verified at IRGeneration time
313 if (outParamIsAssignable && info.fIsSwizzled) {
314 // Found a swizzle; we need to use a helper function here.
315 name = this->getOutParamHelper(function, arguments);
316 break;
317 }
318 }
319 }
320
321 this->write(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400322 this->write("(");
323 const char* separator = "";
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400324 if (this->requirements(function) & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400325 this->write("_in");
326 separator = ", ";
327 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400328 if (this->requirements(function) & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400329 this->write(separator);
330 this->write("_out");
331 separator = ", ";
332 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400333 if (this->requirements(function) & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400334 this->write(separator);
335 this->write("_uniforms");
336 separator = ", ";
337 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400338 if (this->requirements(function) & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400339 this->write(separator);
340 this->write("_globals");
341 separator = ", ";
342 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400343 if (this->requirements(function) & kFragCoord_Requirement) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400344 this->write(separator);
345 this->write("_fragCoord");
346 separator = ", ";
347 }
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400348 for (size_t i = 0; i < arguments.size(); ++i) {
349 const Expression& arg = *arguments[i];
Ethan Nicholascc305772017-10-13 16:17:45 -0400350 this->write(separator);
351 separator = ", ";
Ethan Nicholascc305772017-10-13 16:17:45 -0400352 this->writeExpression(arg, kSequence_Precedence);
353 }
354 this->write(")");
355}
356
John Stilesb21fac22020-12-04 15:36:49 -0500357String MetalCodeGenerator::getInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400358 const Type& type = mat.type();
359 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500360 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400361 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500362 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
363 fWrittenIntrinsics.insert(name);
364 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500365 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500366 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
367 "}"
368 ).c_str());
369 }
370 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400371 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500372 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
373 fWrittenIntrinsics.insert(name);
374 fExtraFunctions.writeText((
375 typeName + " " + name + "(" + typeName + " m) {"
376 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
377 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
378 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
379 " float b01 = a22 * a11 - a12 * a21;"
380 " float b11 = -a22 * a10 + a12 * a20;"
381 " float b21 = a21 * a10 - a11 * a20;"
382 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
383 " return " + typeName +
384 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
385 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
386 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
387 " (1/det);"
388 "}"
389 ).c_str());
390 }
391 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400392 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500393 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
394 fWrittenIntrinsics.insert(name);
395 fExtraFunctions.writeText((
396 typeName + " " + name + "(" + typeName + " m) {"
397 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
398 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
399 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
400 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
401 " float b00 = a00 * a11 - a01 * a10;"
402 " float b01 = a00 * a12 - a02 * a10;"
403 " float b02 = a00 * a13 - a03 * a10;"
404 " float b03 = a01 * a12 - a02 * a11;"
405 " float b04 = a01 * a13 - a03 * a11;"
406 " float b05 = a02 * a13 - a03 * a12;"
407 " float b06 = a20 * a31 - a21 * a30;"
408 " float b07 = a20 * a32 - a22 * a30;"
409 " float b08 = a20 * a33 - a23 * a30;"
410 " float b09 = a21 * a32 - a22 * a31;"
411 " float b10 = a21 * a33 - a23 * a31;"
412 " float b11 = a22 * a33 - a23 * a32;"
413 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
414 " b04 * b07 + b05 * b06;"
415 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
416 " a02 * b10 - a01 * b11 - a03 * b09,"
417 " a31 * b05 - a32 * b04 + a33 * b03,"
418 " a22 * b04 - a21 * b05 - a23 * b03,"
419 " a12 * b08 - a10 * b11 - a13 * b07,"
420 " a00 * b11 - a02 * b08 + a03 * b07,"
421 " a32 * b02 - a30 * b05 - a33 * b01,"
422 " a20 * b05 - a22 * b02 + a23 * b01,"
423 " a10 * b10 - a11 * b08 + a13 * b06,"
424 " a01 * b08 - a00 * b10 - a03 * b06,"
425 " a30 * b04 - a31 * b02 + a33 * b00,"
426 " a21 * b02 - a20 * b04 - a23 * b00,"
427 " a11 * b07 - a10 * b09 - a12 * b06,"
428 " a00 * b09 - a01 * b07 + a02 * b06,"
429 " a31 * b01 - a30 * b03 - a32 * b00,"
430 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
431 "}"
432 ).c_str());
433 }
434 }
John Stilesb21fac22020-12-04 15:36:49 -0500435 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500436}
437
Timothy Liang6403b0e2018-05-17 10:40:04 -0400438void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400439 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400440 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400441 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400442 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400443 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400444 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400445 this->write(SAMPLER_SUFFIX);
446 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400447 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400448 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500449 // have to store the vector in a temp variable to avoid double evaluating it
450 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400451 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500452 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400453 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500454 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400455 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400456 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400457 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400458 this->write(")");
459 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400460 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400461 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500462 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400463 // 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 -0500464 String tmpX = "tmpX" + to_string(fVarCount++);
465 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400466 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400467 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500468 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400469 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500470 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400471 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500472 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400473 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500474 }
Brian Osman46787d52020-11-24 14:18:23 -0500475 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
476 case kDistance_SpecialIntrinsic: {
477 if (arguments[0]->type().columns() == 1) {
478 this->write("abs(");
479 this->writeExpression(*arguments[0], kAdditive_Precedence);
480 this->write(" - ");
481 this->writeExpression(*arguments[1], kAdditive_Precedence);
482 this->write(")");
483 } else {
484 this->write("distance(");
485 this->writeExpression(*arguments[0], kSequence_Precedence);
486 this->write(", ");
487 this->writeExpression(*arguments[1], kSequence_Precedence);
488 this->write(")");
489 }
490 break;
491 }
492 case kDot_SpecialIntrinsic: {
493 if (arguments[0]->type().columns() == 1) {
494 this->write("(");
495 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
496 this->write(" * ");
497 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
498 this->write(")");
499 } else {
500 this->write("dot(");
501 this->writeExpression(*arguments[0], kSequence_Precedence);
502 this->write(", ");
503 this->writeExpression(*arguments[1], kSequence_Precedence);
504 this->write(")");
505 }
506 break;
507 }
508 case kLength_SpecialIntrinsic: {
509 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
510 this->writeExpression(*arguments[0], kSequence_Precedence);
511 this->write(")");
512 break;
513 }
514 case kNormalize_SpecialIntrinsic: {
515 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
516 this->writeExpression(*arguments[0], kSequence_Precedence);
517 this->write(")");
518 break;
519 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400520 default:
521 ABORT("unsupported special intrinsic kind");
522 }
523}
524
John Stilesfcf8cb22020-08-06 14:29:22 -0400525// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
526// Cells that don't exist in the source matrix will be populated with identity-matrix values.
527void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
528 SkASSERT(rows <= 4);
529 SkASSERT(columns <= 4);
530
531 const char* columnSeparator = "";
532 for (int c = 0; c < columns; ++c) {
533 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
534 columnSeparator = "), ";
535
536 // Determine how many values to take from the source matrix for this row.
537 int swizzleLength = 0;
538 if (c < sourceMatrix.columns()) {
539 swizzleLength = std::min<>(rows, sourceMatrix.rows());
540 }
541
542 // Emit all the values from the source matrix row.
543 bool firstItem;
544 switch (swizzleLength) {
545 case 0: firstItem = true; break;
546 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
547 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
548 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
549 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
550 default: SkUNREACHABLE;
551 }
552
553 // Emit the placeholder identity-matrix cells.
554 for (int r = swizzleLength; r < rows; ++r) {
555 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
556 firstItem = false;
557 }
558 }
559
560 fExtraFunctions.writeText(")");
561}
562
563// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
564// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400565void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
566 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400567 size_t argIndex = 0;
568 int argPosition = 0;
569
570 const char* columnSeparator = "";
571 for (int c = 0; c < columns; ++c) {
572 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
573 columnSeparator = "), ";
574
575 const char* rowSeparator = "";
576 for (int r = 0; r < rows; ++r) {
577 fExtraFunctions.writeText(rowSeparator);
578 rowSeparator = ", ";
579
580 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400581 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400582 switch (argType.typeKind()) {
583 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400584 fExtraFunctions.printf("x%zu", argIndex);
585 break;
586 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400587 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400588 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
589 break;
590 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400591 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400592 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
593 argPosition / argType.rows(),
594 argPosition % argType.rows());
595 break;
596 }
597 default: {
598 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
599 fExtraFunctions.writeText("<error>");
600 break;
601 }
602 }
603
604 ++argPosition;
605 if (argPosition >= argType.columns() * argType.rows()) {
606 ++argIndex;
607 argPosition = 0;
608 }
609 } else {
610 SkDEBUGFAIL("not enough arguments for matrix constructor");
611 fExtraFunctions.writeText("<error>");
612 }
613 }
614 }
615
616 if (argPosition != 0 || argIndex != args.size()) {
617 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
618 fExtraFunctions.writeText(", <error>");
619 }
620
621 fExtraFunctions.writeText(")");
622}
623
John Stiles1bdafbf2020-05-28 12:17:20 -0400624// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
625// Keeps track of previously generated constructors so that we won't generate more than one
626// constructor for any given permutation of input argument types. Returns the name of the
627// generated constructor method.
628String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400629 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500630 int columns = matrix.columns();
631 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400632 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400633
634 // Create the helper-method name and use it as our lookup key.
635 String name;
636 name.appendf("float%dx%d_from", columns, rows);
637 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400638 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400639 }
640
641 // If a helper-method has already been synthesized, we don't need to synthesize it again.
642 auto [iter, newlyCreated] = fHelpers.insert(name);
643 if (!newlyCreated) {
644 return name;
645 }
646
647 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
648 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
649 // supply a mixture of scalars and vectors.)
650 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
651
652 size_t argIndex = 0;
653 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400654 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400655 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400656 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400657 argSeparator = ", ";
658 }
659
660 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
661
John Stiles9aeed132020-11-24 17:36:06 -0500662 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400663 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400664 } else {
665 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400666 }
667
John Stilesfcf8cb22020-08-06 14:29:22 -0400668 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500669 return name;
670}
671
672bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
673 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
674 return false;
675 }
676 if (t1.columns() > 1) {
677 return this->canCoerce(t1.componentType(), t2.componentType());
678 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500679 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500680}
681
John Stiles1bdafbf2020-05-28 12:17:20 -0400682bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
683 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500684 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400685 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500686 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400687
688 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
689 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
690 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
691 // scalars can be constructed trivially. In more complex cases, we generate a helper function
692 // that converts our inputs into a properly-shaped matrix.
693 // A matrix construct helper method is always used if any input argument is a matrix.
694 // Helper methods are also necessary when any argument would span multiple rows. For instance:
695 //
696 // float2 x = (1, 2);
697 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
698 // | 2 4 6 |
699 //
700 // float2 x = (2, 3);
701 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
702 // | 2 4 6 |
703 //
704 // float4 x = (1, 2, 3, 4);
705 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
706 // | 2 4 |
707 //
708
709 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400710 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400711 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500712 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400713 return true;
714 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400715 position += expr->type().columns();
716 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400717 // An input argument would span multiple rows; a helper function is required.
718 return true;
719 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400720 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400721 // We've advanced to the end of a row. Wrap to the start of the next row.
722 position = 0;
723 }
724 }
725
726 return false;
727}
728
729void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400730 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400731 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400732 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400733 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400734 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400735 const Type& argType = arg.type();
736 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400737 this->writeExpression(arg, parentPrecedence);
738 return;
739 }
740
741 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
742 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500743 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400744 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400745 this->write("float");
746 this->write(to_string(matrix.columns()));
747 this->write("x");
748 this->write(to_string(matrix.rows()));
749 this->write("(");
750 this->writeExpression(arg, parentPrecedence);
751 this->write(")");
752 return;
753 }
754 }
755
756 // Emit and invoke a matrix-constructor helper method if one is necessary.
757 if (this->matrixConstructHelperIsNeeded(c)) {
758 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000759 this->write("(");
760 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400761 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000762 this->write(separator);
763 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400764 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400765 }
John Stiles1fa15b12020-05-28 17:36:54 +0000766 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400767 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400768 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400769
770 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stiles3dba3ee2020-12-02 23:35:49 -0500771 this->writeBaseType(constructorType);
772 this->disallowArrayTypes(constructorType); // constructors of array types aren't valid exprs
John Stiles1bdafbf2020-05-28 12:17:20 -0400773 this->write("(");
774 const char* separator = "";
775 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400776 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400777 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400778 this->write(separator);
779 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -0500780 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400781 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400782 // Merge scalars and smaller vectors together.
783 if (!scalarCount) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500784 this->writeBaseType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400785 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400786 this->write("(");
787 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400788 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400789 }
790 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400791 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400792 this->write(")");
793 scalarCount = 0;
794 }
795 }
796 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400797}
798
799void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400800 if (fRTHeightName.length()) {
801 this->write("float4(_fragCoord.x, ");
802 this->write(fRTHeightName.c_str());
803 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500804 } else {
805 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
806 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400807}
808
809void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400810 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400811 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400812 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400813 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400814 case SK_FRAGCOORD_BUILTIN:
815 this->writeFragCoord();
816 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400817 case SK_VERTEXID_BUILTIN:
818 this->write("sk_VertexID");
819 break;
820 case SK_INSTANCEID_BUILTIN:
821 this->write("sk_InstanceID");
822 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400823 case SK_CLOCKWISE_BUILTIN:
824 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400825 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400826 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
827 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400828 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400829 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400830 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400831 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400832 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400833 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400834 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400835 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
836 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400837 this->write("_uniforms.");
838 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400839 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400840 }
841 }
Ethan Nicholas78686922020-10-08 06:46:27 -0400842 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400843 }
844}
845
846void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400847 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400848 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -0400849 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400850 this->write("]");
851}
852
853void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400854 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
855 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
856 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400857 this->write(".");
858 }
Timothy Liang7d637782018-06-05 09:58:07 -0400859 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400860 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400861 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400862 break;
863 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400864 if (field->fName == "sk_PointSize") {
865 this->write("_out->sk_PointSize");
866 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -0400867 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -0400868 this->write("_globals->");
869 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
870 this->write("->");
871 }
Timothy Liang651286f2018-06-07 09:55:33 -0400872 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400873 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400874 }
875}
876
877void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400878 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400879 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -0400880 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -0400881 SkASSERT(c >= 0 && c <= 3);
882 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -0400883 }
884}
885
886MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
887 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400888 case Token::Kind::TK_STAR: // fall through
889 case Token::Kind::TK_SLASH: // fall through
890 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
891 case Token::Kind::TK_PLUS: // fall through
892 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
893 case Token::Kind::TK_SHL: // fall through
894 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
895 case Token::Kind::TK_LT: // fall through
896 case Token::Kind::TK_GT: // fall through
897 case Token::Kind::TK_LTEQ: // fall through
898 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
899 case Token::Kind::TK_EQEQ: // fall through
900 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
901 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
902 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
903 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
904 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
905 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
906 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
907 case Token::Kind::TK_EQ: // fall through
908 case Token::Kind::TK_PLUSEQ: // fall through
909 case Token::Kind::TK_MINUSEQ: // fall through
910 case Token::Kind::TK_STAREQ: // fall through
911 case Token::Kind::TK_SLASHEQ: // fall through
912 case Token::Kind::TK_PERCENTEQ: // fall through
913 case Token::Kind::TK_SHLEQ: // fall through
914 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400915 case Token::Kind::TK_BITWISEANDEQ: // fall through
916 case Token::Kind::TK_BITWISEXOREQ: // fall through
917 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
918 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -0400919 default: ABORT("unsupported binary operator");
920 }
921}
922
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500923void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
924 const Type& result) {
925 String key = "TimesEqual" + left.name() + right.name();
926 if (fHelpers.find(key) == fHelpers.end()) {
927 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
928 " left = left * right;\n"
929 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -0400930 "}", String(result.name()).c_str(), String(left.name()).c_str(),
931 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500932 }
933}
934
Ethan Nicholascc305772017-10-13 16:17:45 -0400935void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
936 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -0400937 const Expression& left = *b.left();
938 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400939 const Type& leftType = left.type();
940 const Type& rightType = right.type();
941 Token::Kind op = b.getOperator();
942 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500943 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400944 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400945 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500946 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500947 this->write("all");
948 needParens = true;
949 }
950 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -0400951 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -0500952 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400953 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500954 needParens = true;
955 }
956 break;
957 default:
958 break;
959 }
960 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400961 this->write("(");
962 }
John Stiles9aeed132020-11-24 17:36:06 -0500963 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400964 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500965 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400966 this->writeExpression(left, precedence);
967 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
968 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400969 // This doesn't compile in Metal:
970 // float4 x = float4(1);
971 // x.xy *= float2x2(...);
972 // with the error message "non-const reference cannot bind to vector element",
973 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
974 // as long as the LHS has no side effects, and hope for the best otherwise.
975 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400976 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400977 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -0500978 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400979 SkASSERT(opName.endsWith("="));
980 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -0400981 this->write(" ");
982 } else {
John Stilesd6449e92020-11-30 09:13:23 -0500983 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -0400984 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -0400985 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500986 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400987 this->write(")");
988 }
989}
990
991void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
992 Precedence parentPrecedence) {
993 if (kTernary_Precedence >= parentPrecedence) {
994 this->write("(");
995 }
Ethan Nicholasdd218162020-10-08 05:48:01 -0400996 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400997 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -0400998 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400999 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001000 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001001 if (kTernary_Precedence >= parentPrecedence) {
1002 this->write(")");
1003 }
1004}
1005
1006void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1007 Precedence parentPrecedence) {
1008 if (kPrefix_Precedence >= parentPrecedence) {
1009 this->write("(");
1010 }
John Stilesd6449e92020-11-30 09:13:23 -05001011 this->write(OperatorName(p.getOperator()));
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001012 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001013 if (kPrefix_Precedence >= parentPrecedence) {
1014 this->write(")");
1015 }
1016}
1017
1018void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1019 Precedence parentPrecedence) {
1020 if (kPostfix_Precedence >= parentPrecedence) {
1021 this->write("(");
1022 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001023 this->writeExpression(*p.operand(), kPostfix_Precedence);
John Stilesd6449e92020-11-30 09:13:23 -05001024 this->write(OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001025 if (kPostfix_Precedence >= parentPrecedence) {
1026 this->write(")");
1027 }
1028}
1029
1030void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001031 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001032}
1033
1034void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001035 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001036 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001037 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001038 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001039 }
1040}
1041
1042void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001043 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001044}
1045
1046void MetalCodeGenerator::writeSetting(const Setting& s) {
1047 ABORT("internal error; setting was not folded to a constant during compilation\n");
1048}
1049
John Stiles569249b2020-11-03 12:18:22 -05001050bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001051 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001052 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001053 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001054 switch (fProgram.fKind) {
1055 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001056 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001057 break;
1058 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001059 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001060 break;
1061 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001062 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001063 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001064 }
1065 this->write("(Inputs _in [[stage_in]]");
1066 if (-1 != fUniformBuffer) {
1067 this->write(", constant Uniforms& _uniforms [[buffer(" +
1068 to_string(fUniformBuffer) + ")]]");
1069 }
Brian Osman133724c2020-10-28 14:14:39 -04001070 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001071 if (e->is<GlobalVarDeclaration>()) {
1072 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001073 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1074 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1075 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001076 fErrors.error(decls.fOffset,
1077 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001078 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001079 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001080 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001081 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001082 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001083 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001084 }
1085 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001086 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001087 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001088 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001089 this->write(")]]");
1090 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001091 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001092 this->write(SAMPLER_SUFFIX);
1093 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001094 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001095 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001096 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001097 } else if (e->is<InterfaceBlock>()) {
1098 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001099 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001100 continue;
1101 }
John Stilesbc3c41b2020-12-04 10:52:40 -05001102 if (intf.variable().modifiers().fLayout.fBinding < 0) {
1103 fErrors.error(intf.fOffset,
1104 "Metal interface blocks must have 'layout(binding=...)'");
1105 return false;
1106 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001107 this->write(", constant ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001108 this->writeBaseType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001109 this->write("& " );
1110 this->write(fInterfaceBlockNameMap[&intf]);
1111 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001112 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001113 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001114 }
1115 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001116 if (fProgram.fKind == Program::kFragment_Kind) {
1117 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001118 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001119 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001120 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001121 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001122 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001123 } else if (fProgram.fKind == Program::kVertex_Kind) {
1124 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001125 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001126 separator = ", ";
1127 } else {
John Stiles3dba3ee2020-12-02 23:35:49 -05001128 this->writeBaseType(f.returnType());
1129 this->disallowArrayTypes(f.returnType()); // return types can't be arrays in SkSL/GLSL
Timothy Liang651286f2018-06-07 09:55:33 -04001130 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001131 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001132 this->write("(");
John Stiles569249b2020-11-03 12:18:22 -05001133 Requirements requirements = this->requirements(f);
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001134 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001135 this->write("Inputs _in");
1136 separator = ", ";
1137 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001138 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001139 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -04001140 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -04001141 separator = ", ";
1142 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001143 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001144 this->write(separator);
1145 this->write("Uniforms _uniforms");
1146 separator = ", ";
1147 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001148 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001149 this->write(separator);
1150 this->write("thread Globals* _globals");
1151 separator = ", ";
1152 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001153 if (requirements & kFragCoord_Requirement) {
1154 this->write(separator);
1155 this->write("float4 _fragCoord");
1156 separator = ", ";
1157 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 }
John Stiles569249b2020-11-03 12:18:22 -05001159 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001160 this->write(separator);
1161 separator = ", ";
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001162 this->writeModifiers(param->modifiers(), false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001163 const Type* type = &param->type();
John Stiles3dba3ee2020-12-02 23:35:49 -05001164 this->writeBaseType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001165 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001166 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001167 }
Timothy Liang651286f2018-06-07 09:55:33 -04001168 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001169 this->writeName(param->name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001170 this->writeArrayDimensions(*type);
Ethan Nicholascc305772017-10-13 16:17:45 -04001171 }
John Stiles569249b2020-11-03 12:18:22 -05001172 this->write(")");
1173 return true;
1174}
Ethan Nicholascc305772017-10-13 16:17:45 -04001175
John Stiles569249b2020-11-03 12:18:22 -05001176void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1177 this->writeFunctionDeclaration(f.declaration());
1178 this->writeLine(";");
1179}
1180
John Stiles986c7fb2020-12-01 14:44:56 -05001181static bool is_block_ending_with_return(const Statement* stmt) {
1182 // This function detects (potentially nested) blocks that end in a return statement.
1183 if (!stmt->is<Block>()) {
1184 return false;
1185 }
1186 const StatementArray& block = stmt->as<Block>().children();
1187 for (int index = block.count(); index--; ) {
1188 const Statement& stmt = *block[index];
1189 if (stmt.is<ReturnStatement>()) {
1190 return true;
1191 }
1192 if (stmt.is<Block>()) {
1193 return is_block_ending_with_return(&stmt);
1194 }
1195 if (!stmt.is<Nop>()) {
1196 break;
1197 }
1198 }
1199 return false;
1200}
1201
John Stiles569249b2020-11-03 12:18:22 -05001202void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001203 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001204
John Stiles569249b2020-11-03 12:18:22 -05001205 if (!this->writeFunctionDeclaration(f.declaration())) {
1206 return;
1207 }
1208
John Stiles986c7fb2020-12-01 14:44:56 -05001209 fCurrentFunction = &f.declaration();
1210 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1211
John Stiles569249b2020-11-03 12:18:22 -05001212 this->writeLine(" {");
1213
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001214 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001215 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001216 this->writeLine(" Outputs _outputStruct;");
1217 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001218 }
John Stilesc67b3622020-05-28 17:53:13 -04001219
Ethan Nicholascc305772017-10-13 16:17:45 -04001220 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001221 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001222 {
1223 AutoOutputStream outputToBuffer(this, &buffer);
1224 fIndentation++;
1225 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1226 if (!stmt->isEmpty()) {
1227 this->writeStatement(*stmt);
1228 this->writeLine();
1229 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001230 }
John Stiles44532372020-12-07 12:33:55 -05001231 if (f.declaration().name() == "main") {
1232 // If the main function doesn't end with a return, we need to synthesize one here.
1233 if (!is_block_ending_with_return(f.body().get())) {
1234 this->writeReturnStatementFromMain();
1235 this->writeLine("");
1236 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001237 }
John Stiles44532372020-12-07 12:33:55 -05001238 fIndentation--;
1239 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001240 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001241 this->write(fFunctionHeader);
1242 this->write(buffer.str());
1243}
1244
1245void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1246 bool globalContext) {
1247 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1248 this->write("thread ");
1249 }
1250 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001251 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001252 }
1253}
1254
1255void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001256 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001257 return;
1258 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001259 this->writeModifiers(intf.variable().modifiers(), true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001260 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001261 this->writeLine(intf.typeName() + " {");
1262 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001263 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001264 structType = &structType->componentType();
1265 }
John Stiles3dba3ee2020-12-02 23:35:49 -05001266 fWrittenStructs.push_back(structType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001267 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001268 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001269 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001270 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001271 }
1272 fIndentation--;
1273 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001274 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001275 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001276 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001277 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001278 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001279 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001280 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001281 } else if (intf.arraySize() == Type::kUnsizedArray){
1282 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001283 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001284 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001285 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001286 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001287 }
1288 this->writeLine(";");
1289}
1290
Timothy Liangdc89f192018-06-13 09:20:31 -04001291void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1292 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001293 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001294 int currentOffset = 0;
1295 for (const auto& field: fields) {
1296 int fieldOffset = field.fModifiers.fLayout.fOffset;
1297 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001298 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001299 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1300 return;
1301 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001302 if (fieldOffset != -1) {
1303 if (currentOffset > fieldOffset) {
1304 fErrors.error(parentOffset,
1305 "offset of field '" + field.fName + "' must be at least " +
1306 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001307 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001308 } else if (currentOffset < fieldOffset) {
1309 this->write("char pad");
1310 this->write(to_string(fPaddingCount++));
1311 this->write("[");
1312 this->write(to_string(fieldOffset - currentOffset));
1313 this->writeLine("];");
1314 currentOffset = fieldOffset;
1315 }
1316 int alignment = memoryLayout.alignment(*fieldType);
1317 if (fieldOffset % alignment) {
1318 fErrors.error(parentOffset,
1319 "offset of field '" + field.fName + "' must be a multiple of " +
1320 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001321 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001322 }
1323 }
Brian Osman8609a242020-09-08 14:01:49 -04001324 size_t fieldSize = memoryLayout.size(*fieldType);
1325 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1326 fErrors.error(parentOffset, "field offset overflow");
1327 return;
1328 }
1329 currentOffset += fieldSize;
Timothy Liangdc89f192018-06-13 09:20:31 -04001330 this->writeModifiers(field.fModifiers, false);
John Stiles3dba3ee2020-12-02 23:35:49 -05001331 this->writeBaseType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001332 this->write(" ");
1333 this->writeName(field.fName);
John Stiles3dba3ee2020-12-02 23:35:49 -05001334 this->writeArrayDimensions(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001335 this->writeLine(";");
1336 if (parentIntf) {
1337 fInterfaceBlockMap[&field] = parentIntf;
1338 }
1339 }
1340}
1341
Ethan Nicholascc305772017-10-13 16:17:45 -04001342void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1343 this->writeExpression(value, kTopLevel_Precedence);
1344}
1345
Timothy Liang651286f2018-06-07 09:55:33 -04001346void MetalCodeGenerator::writeName(const String& name) {
1347 if (fReservedWords.find(name) != fReservedWords.end()) {
1348 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1349 }
1350 this->write(name);
1351}
1352
Brian Osmanc0213602020-10-06 14:43:32 -04001353void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001354 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001355 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001356 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001357 this->writeModifiers(var.var().modifiers(), global);
John Stiles3dba3ee2020-12-02 23:35:49 -05001358 this->writeBaseType(var.baseType());
1359 this->disallowArrayTypes(var.baseType()); // `float[2] x` shouldn't be possible (invalid SkSL)
Brian Osmanc0213602020-10-06 14:43:32 -04001360 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001361 this->writeName(var.var().name());
John Stiles62a56462020-12-03 10:41:58 -05001362 if (var.arraySize() > 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001363 this->write("[");
John Stiles62a56462020-12-03 10:41:58 -05001364 this->write(to_string(var.arraySize()));
Brian Osmanc0213602020-10-06 14:43:32 -04001365 this->write("]");
John Stiles62a56462020-12-03 10:41:58 -05001366 } else if (var.arraySize() == Type::kUnsizedArray){
1367 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001368 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001369 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001370 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001371 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001372 }
1373 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001374}
1375
1376void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001377 switch (s.kind()) {
1378 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001379 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001380 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001381 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001382 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001383 this->write(";");
1384 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001385 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001386 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001387 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001388 case Statement::Kind::kVarDeclaration:
1389 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001390 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001391 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001392 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001393 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001394 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001395 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001396 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001397 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001398 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001399 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001400 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001401 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001402 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001403 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001404 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001405 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001406 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001407 this->write("break;");
1408 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001409 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001410 this->write("continue;");
1411 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001412 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001413 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001414 break;
John Stiles98c1f822020-09-09 14:18:53 -04001415 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001416 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001417 this->write(";");
1418 break;
1419 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001420#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001421 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001422#endif
1423 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001424 }
1425}
1426
Ethan Nicholascc305772017-10-13 16:17:45 -04001427void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001428 bool isScope = b.isScope();
1429 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001430 this->writeLine("{");
1431 fIndentation++;
1432 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001433 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1434 if (!stmt->isEmpty()) {
1435 this->writeStatement(*stmt);
1436 this->writeLine();
1437 }
1438 }
1439 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001440 fIndentation--;
1441 this->write("}");
1442 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001443}
1444
1445void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1446 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001447 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001448 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001449 this->writeStatement(*stmt.ifTrue());
1450 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001451 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001452 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001453 }
1454}
1455
1456void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1457 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001458 if (f.initializer() && !f.initializer()->isEmpty()) {
1459 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001460 } else {
1461 this->write("; ");
1462 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001463 if (f.test()) {
1464 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001465 }
1466 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001467 if (f.next()) {
1468 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001469 }
1470 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001471 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001472}
1473
1474void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1475 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001476 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001477 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001478 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001479}
1480
1481void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1482 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001483 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001484 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001485 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001486 this->write(");");
1487}
1488
1489void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1490 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001491 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001492 this->writeLine(") {");
1493 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001494 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1495 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001496 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001497 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001498 this->writeLine(":");
1499 } else {
1500 this->writeLine("default:");
1501 }
1502 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001503 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001504 this->writeStatement(*stmt);
1505 this->writeLine();
1506 }
1507 fIndentation--;
1508 }
1509 fIndentation--;
1510 this->write("}");
1511}
1512
John Stiles986c7fb2020-12-01 14:44:56 -05001513void MetalCodeGenerator::writeReturnStatementFromMain() {
1514 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
1515 switch (fProgram.fKind) {
1516 case Program::kFragment_Kind:
1517 this->write("return *_out;");
1518 break;
1519 case Program::kVertex_Kind:
1520 this->write("return (_out->sk_Position.y = -_out->sk_Position.y, *_out);");
1521 break;
1522 default:
1523 SkDEBUGFAIL("unsupported kind of program");
1524 }
1525}
1526
Ethan Nicholascc305772017-10-13 16:17:45 -04001527void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stiles986c7fb2020-12-01 14:44:56 -05001528 if (fCurrentFunction && fCurrentFunction->name() == "main") {
1529 if (r.expression()) {
1530 fErrors.error(r.fOffset, "Metal does not support returning values from main()");
1531 }
1532 this->writeReturnStatementFromMain();
1533 return;
1534 }
1535
Ethan Nicholascc305772017-10-13 16:17:45 -04001536 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001537 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001538 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001539 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001540 }
1541 this->write(";");
1542}
1543
1544void MetalCodeGenerator::writeHeader() {
1545 this->write("#include <metal_stdlib>\n");
1546 this->write("#include <simd/simd.h>\n");
1547 this->write("using namespace metal;\n");
1548}
1549
1550void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001551 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001552 if (e->is<GlobalVarDeclaration>()) {
1553 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001554 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001555 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001556 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001557 if (-1 == fUniformBuffer) {
1558 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001559 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001560 if (-1 == fUniformBuffer) {
1561 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1562 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001563 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001564 if (-1 == fUniformBuffer) {
1565 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1566 "the same 'layout(set=...)'");
1567 }
1568 }
1569 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001570 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001571 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001572 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001573 this->writeArrayDimensions(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001574 this->write(";\n");
1575 }
1576 }
1577 }
1578 if (-1 != fUniformBuffer) {
1579 this->write("};\n");
1580 }
1581}
1582
1583void MetalCodeGenerator::writeInputStruct() {
1584 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001585 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001586 if (e->is<GlobalVarDeclaration>()) {
1587 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001588 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001589 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1590 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001591 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001592 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001593 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001594 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001595 this->writeArrayDimensions(var.type());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001596 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001597 if (fProgram.fKind == Program::kVertex_Kind) {
1598 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001599 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001600 } else if (fProgram.fKind == Program::kFragment_Kind) {
1601 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001602 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001603 }
1604 }
1605 this->write(";\n");
1606 }
1607 }
1608 }
1609 this->write("};\n");
1610}
1611
1612void MetalCodeGenerator::writeOutputStruct() {
1613 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001614 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001615 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001616 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001617 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001618 }
Brian Osman133724c2020-10-28 14:14:39 -04001619 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001620 if (e->is<GlobalVarDeclaration>()) {
1621 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001622 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001623 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1624 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001625 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001626 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001627 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001628 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001629 this->writeArrayDimensions(var.type());
John Stiles842b3592020-12-01 10:36:37 -05001630
1631 int location = var.modifiers().fLayout.fLocation;
1632 if (location < 0) {
1633 fErrors.error(var.fOffset,
1634 "Metal out variables must have 'layout(location=...)'");
1635 } else if (fProgram.fKind == Program::kVertex_Kind) {
1636 this->write(" [[user(locn" + to_string(location) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001637 } else if (fProgram.fKind == Program::kFragment_Kind) {
John Stiles842b3592020-12-01 10:36:37 -05001638 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001639 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001640 if (colorIndex) {
1641 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001642 }
Brian Osmanc0213602020-10-06 14:43:32 -04001643 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001644 }
1645 this->write(";\n");
1646 }
1647 }
Timothy Liang7d637782018-06-05 09:58:07 -04001648 }
1649 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001650 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001651 }
1652 this->write("};\n");
1653}
1654
1655void MetalCodeGenerator::writeInterfaceBlocks() {
1656 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001657 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001658 if (e->is<InterfaceBlock>()) {
1659 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001660 wroteInterfaceBlock = true;
1661 }
1662 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001663 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001664 this->writeLine("struct sksl_synthetic_uniforms {");
1665 this->writeLine(" float u_skRTHeight;");
1666 this->writeLine("};");
1667 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001668}
1669
John Stilesdc75a972020-11-25 16:24:55 -05001670void MetalCodeGenerator::writeStructDefinitions() {
1671 for (const ProgramElement* e : fProgram.elements()) {
1672 if (e->is<StructDefinition>()) {
1673 if (this->writeStructDefinition(e->as<StructDefinition>().type())) {
1674 this->writeLine(";");
1675 }
1676 } else if (e->is<GlobalVarDeclaration>()) {
1677 // If a global var declaration introduces a struct type, we need to write that type
1678 // here, since globals are all embedded in a sub-struct.
1679 const Type* type = &e->as<GlobalVarDeclaration>().declaration()
1680 ->as<VarDeclaration>().baseType();
John Stilesc0c51062020-12-03 17:16:29 -05001681 if (type->isStruct()) {
John Stilesdc75a972020-11-25 16:24:55 -05001682 if (this->writeStructDefinition(*type)) {
1683 this->writeLine(";");
1684 }
1685 }
1686 }
1687 }
1688}
1689
John Stilescdcdb042020-07-06 09:03:51 -04001690void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1691 // Visit the interface blocks.
1692 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05001693 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04001694 }
Brian Osman133724c2020-10-28 14:14:39 -04001695 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001696 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001697 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001698 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001699 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1700 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1701 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001702 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001703 var.type().typeKind() == Type::TypeKind::kSampler) {
1704 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1705 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001706 visitor->visitTexture(var.type(), var.name());
1707 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04001708 } else {
1709 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001710 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001711 }
1712 }
1713 }
John Stilescdcdb042020-07-06 09:03:51 -04001714}
1715
1716void MetalCodeGenerator::writeGlobalStruct() {
1717 class : public GlobalStructVisitor {
1718 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001719 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001720 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001721 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001722 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001723 fCodeGen->write("* ");
1724 fCodeGen->writeName(blockName);
1725 fCodeGen->write(";\n");
1726 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001727 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001728 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001729 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001730 fCodeGen->writeBaseType(type);
John Stilescdcdb042020-07-06 09:03:51 -04001731 fCodeGen->write(" ");
1732 fCodeGen->writeName(name);
John Stiles3dba3ee2020-12-02 23:35:49 -05001733 fCodeGen->writeArrayDimensions(type);
John Stilescdcdb042020-07-06 09:03:51 -04001734 fCodeGen->write(";\n");
1735 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001736 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001737 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001738 fCodeGen->write(" sampler ");
1739 fCodeGen->writeName(name);
1740 fCodeGen->write(";\n");
1741 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001742 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001743 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001744 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001745 fCodeGen->writeBaseType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001746 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001747 fCodeGen->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001748 fCodeGen->writeArrayDimensions(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001749 fCodeGen->write(";\n");
1750 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001751 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04001752 if (fFirst) {
1753 fCodeGen->write("struct Globals {\n");
1754 fFirst = false;
1755 }
1756 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001757 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04001758 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05001759 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04001760 fFirst = true;
1761 }
1762 }
1763
1764 MetalCodeGenerator* fCodeGen = nullptr;
1765 bool fFirst = true;
1766 } visitor;
1767
1768 visitor.fCodeGen = this;
1769 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05001770 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04001771}
1772
1773void MetalCodeGenerator::writeGlobalInit() {
1774 class : public GlobalStructVisitor {
1775 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001776 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04001777 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001778 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001779 fCodeGen->write("&");
1780 fCodeGen->writeName(blockName);
1781 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001782 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001783 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001784 fCodeGen->writeName(name);
1785 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001786 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001787 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001788 fCodeGen->writeName(name);
1789 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001790 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001791 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001792 if (value) {
1793 fCodeGen->writeVarInitializer(var, *value);
1794 } else {
1795 fCodeGen->write("{}");
1796 }
1797 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001798 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04001799 if (fFirst) {
1800 fCodeGen->write(" Globals globalStruct{");
1801 fFirst = false;
1802 } else {
1803 fCodeGen->write(", ");
1804 }
1805 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001806 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04001807 if (!fFirst) {
1808 fCodeGen->writeLine("};");
1809 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
1810 fCodeGen->writeLine(" (void)_globals;");
1811 }
1812 }
1813 MetalCodeGenerator* fCodeGen = nullptr;
1814 bool fFirst = true;
1815 } visitor;
1816
1817 visitor.fCodeGen = this;
1818 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05001819 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04001820}
1821
Ethan Nicholascc305772017-10-13 16:17:45 -04001822void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001823 switch (e.kind()) {
1824 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04001825 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001826 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001827 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
1828 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1829 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04001830 if (-1 == builtin) {
1831 // normal var
1832 this->writeVarDeclaration(decl, true);
1833 this->writeLine();
1834 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1835 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04001836 }
1837 break;
1838 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001839 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04001840 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001841 break;
John Stilesdc75a972020-11-25 16:24:55 -05001842 case ProgramElement::Kind::kStructDefinition:
1843 // Handled in writeStructDefinitions. Do nothing.
1844 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001845 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04001846 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001847 break;
John Stiles569249b2020-11-03 12:18:22 -05001848 case ProgramElement::Kind::kFunctionPrototype:
1849 this->writeFunctionPrototype(e.as<FunctionPrototype>());
1850 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001851 case ProgramElement::Kind::kModifiers:
Ethan Nicholas077050b2020-10-13 10:30:20 -04001852 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(), true);
Ethan Nicholascc305772017-10-13 16:17:45 -04001853 this->writeLine(";");
1854 break;
John Stiles712fd6b2020-11-25 22:25:43 -05001855 case ProgramElement::Kind::kEnum:
1856 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001857 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001858#ifdef SK_DEBUG
1859 ABORT("unsupported program element: %s\n", e.description().c_str());
1860#endif
1861 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001862 }
1863}
1864
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001865MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
1866 if (!e) {
1867 return kNo_Requirements;
1868 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001869 switch (e->kind()) {
1870 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04001871 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04001872 Requirements result = this->requirements(f.function());
1873 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001874 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001875 }
1876 return result;
1877 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001878 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001879 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04001880 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001881 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001882 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001883 }
1884 return result;
1885 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001886 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04001887 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001888 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001889 return kGlobals_Requirement;
1890 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001891 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001892 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001893 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001894 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001895 case Expression::Kind::kBinary: {
1896 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04001897 return this->requirements(bin.left().get()) |
1898 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001899 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001900 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04001901 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001902 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001903 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001904 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001905 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001906 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001907 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001908 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04001909 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04001910 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
1911 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001912 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001913 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04001914 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04001915 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04001916 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001917 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001918 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001919 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001920 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001921 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001922 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001923 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001924 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04001925 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001926 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001927 } else {
1928 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001929 }
1930 }
1931 return result;
1932 }
1933 default:
1934 return kNo_Requirements;
1935 }
1936}
1937
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001938MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
1939 if (!s) {
1940 return kNo_Requirements;
1941 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001942 switch (s->kind()) {
1943 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04001944 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001945 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001946 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001947 }
1948 return result;
1949 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001950 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04001951 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001952 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04001953 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001954 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001955 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04001956 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04001957 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001958 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001959 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001960 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04001961 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001962 return this->requirements(i.test().get()) |
1963 this->requirements(i.ifTrue().get()) |
1964 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001965 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001966 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04001967 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001968 return this->requirements(f.initializer().get()) |
1969 this->requirements(f.test().get()) |
1970 this->requirements(f.next().get()) |
1971 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001972 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001973 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04001974 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001975 return this->requirements(w.test().get()) |
1976 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001977 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001978 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04001979 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001980 return this->requirements(d.test().get()) |
1981 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001982 }
Ethan Nicholase6592142020-09-08 10:22:09 -04001983 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04001984 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001985 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04001986 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
1987 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04001988 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04001989 }
1990 }
1991 return result;
1992 }
1993 default:
1994 return kNo_Requirements;
1995 }
1996}
1997
1998MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04001999 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002000 return kNo_Requirements;
2001 }
2002 auto found = fRequirements.find(&f);
2003 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002004 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002005 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002006 if (e->is<FunctionDefinition>()) {
2007 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002008 if (&def.declaration() == &f) {
2009 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002010 fRequirements[&f] = reqs;
2011 return reqs;
2012 }
2013 }
2014 }
John Stiles569249b2020-11-03 12:18:22 -05002015 // We never found a definition for this declared function, but it's legal to prototype a
2016 // function without ever giving a definition, as long as you don't call it.
2017 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002018 }
2019 return found->second;
2020}
2021
Timothy Liangb8eeb802018-07-23 16:46:16 -04002022bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04002023 fProgramKind = fProgram.fKind;
Ethan Nicholascc305772017-10-13 16:17:45 -04002024
John Stiles44532372020-12-07 12:33:55 -05002025 StringStream header;
2026 {
2027 AutoOutputStream outputToHeader(this, &header, &fIndentation);
2028 this->writeHeader();
2029 this->writeStructDefinitions();
2030 this->writeUniformStruct();
2031 this->writeInputStruct();
2032 this->writeOutputStruct();
2033 this->writeInterfaceBlocks();
2034 this->writeGlobalStruct();
2035 }
2036 StringStream body;
2037 {
2038 AutoOutputStream outputToBody(this, &body, &fIndentation);
2039 for (const ProgramElement* e : fProgram.elements()) {
2040 this->writeProgramElement(*e);
2041 }
2042 }
2043 write_stringstream(header, *fOut);
2044 write_stringstream(fExtraFunctions, *fOut);
2045 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002046 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002047}
2048
John Stilesa6841be2020-08-06 14:11:56 -04002049} // namespace SkSL