blob: 3e5daae9dc9c44a8d567e455757b1740e2263bf7 [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
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/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"
John Stiles7384b372021-04-01 13:48:15 -040013#include "src/sksl/ir/SkSLConstructorArray.h"
John Stilese3ae9682021-08-05 10:35:01 -040014#include "src/sksl/ir/SkSLConstructorArrayCast.h"
John Stiles8cad6372021-04-07 12:31:13 -040015#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stiles7384b372021-04-01 13:48:15 -040016#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040017#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040018#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040019#include "src/sksl/ir/SkSLConstructorStruct.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/sksl/ir/SkSLExpressionStatement.h"
21#include "src/sksl/ir/SkSLExtension.h"
22#include "src/sksl/ir/SkSLIndexExpression.h"
23#include "src/sksl/ir/SkSLModifiersDeclaration.h"
24#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050025#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050026#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040027
Brian Osmanc262a122020-08-06 16:34:34 -040028#include <algorithm>
29
Ethan Nicholascc305772017-10-13 16:17:45 -040030namespace SkSL {
31
John Stiles45990502021-02-16 10:55:27 -050032const char* MetalCodeGenerator::OperatorName(Operator op) {
33 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050034 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050035 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050036 }
37}
38
John Stilescdcdb042020-07-06 09:03:51 -040039class MetalCodeGenerator::GlobalStructVisitor {
40public:
41 virtual ~GlobalStructVisitor() = default;
Ethan Nicholas962dec42021-06-10 13:06:39 -040042 virtual void visitInterfaceBlock(const InterfaceBlock& block, skstd::string_view blockName) = 0;
43 virtual void visitTexture(const Type& type, skstd::string_view name) = 0;
44 virtual void visitSampler(const Type& type, skstd::string_view name) = 0;
John Stilesfdb8dbe2020-12-04 11:00:03 -050045 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040046};
47
Ethan Nicholas962dec42021-06-10 13:06:39 -040048void MetalCodeGenerator::write(skstd::string_view s) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -040049 if (s.empty()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040050 return;
51 }
52 if (fAtLineStart) {
53 for (int i = 0; i < fIndentation; i++) {
54 fOut->writeText(" ");
55 }
56 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -040057 fOut->writeText(String(s).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -040058 fAtLineStart = false;
59}
60
Ethan Nicholas962dec42021-06-10 13:06:39 -040061void MetalCodeGenerator::writeLine(skstd::string_view s) {
Ethan Nicholascc305772017-10-13 16:17:45 -040062 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050063 fOut->writeText(fLineEnding);
64 fAtLineStart = true;
65}
66
67void MetalCodeGenerator::finishLine() {
68 if (!fAtLineStart) {
69 this->writeLine();
70 }
Ethan Nicholascc305772017-10-13 16:17:45 -040071}
72
73void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040074 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040075}
76
Ethan Nicholas45fa8102020-01-13 10:58:49 -050077String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040078 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -050079 case Type::TypeKind::kArray:
80 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
81 return String::printf("array<%s, %d>",
82 this->typeName(type.componentType()).c_str(), type.columns());
83
Ethan Nicholase6592142020-09-08 10:22:09 -040084 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050085 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -050086
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050088 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
89 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -050090
Ethan Nicholase6592142020-09-08 10:22:09 -040091 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -050092 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -050093
Ethan Nicholascc305772017-10-13 16:17:45 -040094 default:
John Stiles7b2b8582021-08-09 14:20:54 -040095 // We currently only support full-precision types in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -050096 if (type == *fContext.fTypes.fHalf) {
John Stiles7b2b8582021-08-09 14:20:54 -040097 return "float";
Timothy Liang7d637782018-06-05 09:58:07 -040098 }
John Stiles7b2b8582021-08-09 14:20:54 -040099 if (type == *fContext.fTypes.fShort) {
100 return "int";
101 }
102 if (type == *fContext.fTypes.fUShort) {
103 return "uint";
104 }
105 return String(type.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400106 }
107}
108
Brian Osman02bc5222021-01-28 11:00:20 -0500109void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
110 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500111 this->writeLine("struct " + type.name() + " {");
112 fIndentation++;
113 this->writeFields(type.fields(), type.fOffset);
114 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500115 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500116}
117
John Stilesb4418502021-02-04 10:57:08 -0500118void MetalCodeGenerator::writeType(const Type& type) {
119 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500120}
121
Ethan Nicholascc305772017-10-13 16:17:45 -0400122void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (expr.kind()) {
124 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400125 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400127 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400128 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400129 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
130 break;
John Stilese3ae9682021-08-05 10:35:01 -0400131 case Expression::Kind::kConstructorArrayCast:
132 this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), parentPrecedence);
133 break;
John Stiles8cad6372021-04-07 12:31:13 -0400134 case Expression::Kind::kConstructorCompound:
135 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400136 break;
137 case Expression::Kind::kConstructorDiagonalMatrix:
138 case Expression::Kind::kConstructorSplat:
139 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400140 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400141 case Expression::Kind::kConstructorMatrixResize:
142 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
143 parentPrecedence);
144 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400145 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400146 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400147 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400148 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400149 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400150 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400151 break;
John Stiles7591d4b2021-09-13 13:32:06 -0400152 case Expression::Kind::kLiteral:
153 this->writeLiteral(expr.as<Literal>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400154 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400155 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400156 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400159 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400162 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400163 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400165 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400167 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400168 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400176 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400177 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400178 break;
179 default:
John Stileseada7bc2021-02-02 16:29:32 -0500180 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500181 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400182 }
183}
184
John Stiles06b84ef2020-12-09 12:35:48 -0500185String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
186 const ExpressionArray& arguments,
187 const SkTArray<VariableReference*>& outVars) {
188 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
189 const FunctionDeclaration& function = call.function();
190
John Stilese1068342021-03-22 11:57:41 -0400191 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
192 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500193 const char* separator = "";
194
195 // Emit a prototype for the function we'll be calling through to in our helper.
196 if (!function.isBuiltin()) {
197 this->writeFunctionDeclaration(function);
198 this->writeLine(";");
199 }
200
201 // Synthesize a helper function that takes the same inputs as `function`, except in places where
202 // `outVars` is non-null; in those places, we take the type of the VariableReference.
203 //
204 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500205 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500206 this->write(" ");
207 this->write(name);
208 this->write("(");
209 this->writeFunctionRequirementParams(function, separator);
210
211 SkASSERT(outVars.size() == arguments.size());
212 SkASSERT(outVars.size() == function.parameters().size());
213
John Stiles73e2c892021-02-13 13:58:01 -0500214 // We need to detect cases where the caller passes the same variable as an out-param more than
215 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
216 // redundant input parameter entirely, and not give it any name.)
217 std::unordered_set<const Variable*> writtenVars;
218
John Stiles06b84ef2020-12-09 12:35:48 -0500219 for (int index = 0; index < arguments.count(); ++index) {
220 this->write(separator);
221 separator = ", ";
222
223 const Variable* param = function.parameters()[index];
Brian Osman58134e12021-05-13 14:51:07 -0400224 this->writeModifiers(param->modifiers());
John Stiles06b84ef2020-12-09 12:35:48 -0500225
226 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500227 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500228
229 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
230 this->write("&");
231 }
232 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500233 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
234 if (didInsert) {
235 this->write(" ");
236 fIgnoreVariableReferenceModifiers = true;
237 this->writeVariableReference(*outVars[index]);
238 fIgnoreVariableReferenceModifiers = false;
239 }
John Stiles06b84ef2020-12-09 12:35:48 -0500240 } else {
241 this->write(" _var");
242 this->write(to_string(index));
243 }
John Stiles06b84ef2020-12-09 12:35:48 -0500244 }
245 this->writeLine(") {");
246
247 ++fIndentation;
248 for (int index = 0; index < outVars.count(); ++index) {
249 if (!outVars[index]) {
250 continue;
251 }
252 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500253 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500254 this->write(" _var");
255 this->write(to_string(index));
256
257 const Variable* param = function.parameters()[index];
258 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
259 this->write(" = ");
260 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500261 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500262 fIgnoreVariableReferenceModifiers = false;
263 }
264
265 this->writeLine(";");
266 }
267
John Stilesf7410bd2021-01-19 13:07:55 -0500268 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500269 bool hasResult = (call.type().name() != "void");
270 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500271 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500272 this->write(" _skResult = ");
273 }
274
John Stilese1068342021-03-22 11:57:41 -0400275 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500276 this->write("(");
277 separator = "";
278 this->writeFunctionRequirementArgs(function, separator);
279
280 for (int index = 0; index < arguments.count(); ++index) {
281 this->write(separator);
282 separator = ", ";
283
284 this->write("_var");
285 this->write(to_string(index));
286 }
287 this->writeLine(");");
288
289 for (int index = 0; index < outVars.count(); ++index) {
290 if (!outVars[index]) {
291 continue;
292 }
293 // outParam.zyx = _var2;
294 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500295 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500296 fIgnoreVariableReferenceModifiers = false;
297 this->write(" = _var");
298 this->write(to_string(index));
299 this->writeLine(";");
300 }
301
302 if (hasResult) {
303 this->writeLine("return _skResult;");
304 }
305
306 --fIndentation;
307 this->writeLine("}");
308
309 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500310}
311
John Stilesf64e4072020-12-10 10:34:27 -0500312String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
313 return "as_type<" + outType.displayName() + ">";
314}
315
Ethan Nicholascc305772017-10-13 16:17:45 -0400316void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400317 const FunctionDeclaration& function = c.function();
John Stiles496b7d12021-05-06 10:26:45 -0400318
319 // Many intrinsics need to be rewritten in Metal.
320 if (function.isIntrinsic()) {
321 if (this->writeIntrinsicCall(c, function.intrinsicKind())) {
John Stiles89ac7c22020-12-30 17:47:31 -0500322 return;
323 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400324 }
John Stilesb21fac22020-12-04 15:36:49 -0500325
John Stilesd7199b22020-12-30 16:22:58 -0500326 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
327 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
328 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
329 // allow a swizzle to be passed to a `floatN&`.)
330 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500331 const std::vector<const Variable*>& parameters = function.parameters();
332 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500333
334 bool foundOutParam = false;
335 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500336 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500337
338 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500339 // If this is an out parameter...
340 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500341 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500342 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500343 // Assignability was verified at IRGeneration time, so this should always succeed.
344 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
345 outVars[index] = info.fAssignedVar;
346 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500347 }
348 }
349
John Stiles06b84ef2020-12-09 12:35:48 -0500350 if (foundOutParam) {
351 // Out parameters need to be written back to at the end of the function. To do this, we
352 // synthesize a helper function which evaluates the out-param expression into a temporary
353 // variable, calls the original function, then writes the temp var back into the out param
354 // using the original out-param expression. (This lets us support things like swizzles and
355 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500356 this->write(getOutParamHelper(c, arguments, outVars));
357 } else {
John Stilese1068342021-03-22 11:57:41 -0400358 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500359 }
360
Ethan Nicholascc305772017-10-13 16:17:45 -0400361 this->write("(");
362 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500363 this->writeFunctionRequirementArgs(function, separator);
364 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400365 this->write(separator);
366 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500367
368 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500369 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500370 } else {
Brian Osman00185012021-02-04 16:07:11 -0500371 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500372 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400373 }
374 this->write(")");
375}
376
Brian Osman964f0a02020-12-29 10:15:22 -0500377static constexpr char kInverse2x2[] = R"(
378float2x2 float2x2_inverse(float2x2 m) {
379 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
380}
381)";
382
383static constexpr char kInverse3x3[] = R"(
384float3x3 float3x3_inverse(float3x3 m) {
385 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
386 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
387 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
388 float b01 = a22*a11 - a12*a21;
389 float b11 = -a22*a10 + a12*a20;
390 float b21 = a21*a10 - a11*a20;
391 float det = a00*b01 + a01*b11 + a02*b21;
392 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
393 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
394 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
395}
396)";
397
398static constexpr char kInverse4x4[] = R"(
399float4x4 float4x4_inverse(float4x4 m) {
400 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
401 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
402 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
403 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
404 float b00 = a00*a11 - a01*a10;
405 float b01 = a00*a12 - a02*a10;
406 float b02 = a00*a13 - a03*a10;
407 float b03 = a01*a12 - a02*a11;
408 float b04 = a01*a13 - a03*a11;
409 float b05 = a02*a13 - a03*a12;
410 float b06 = a20*a31 - a21*a30;
411 float b07 = a20*a32 - a22*a30;
412 float b08 = a20*a33 - a23*a30;
413 float b09 = a21*a32 - a22*a31;
414 float b10 = a21*a33 - a23*a31;
415 float b11 = a22*a33 - a23*a32;
416 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
417 return float4x4(a11*b11 - a12*b10 + a13*b09,
418 a02*b10 - a01*b11 - a03*b09,
419 a31*b05 - a32*b04 + a33*b03,
420 a22*b04 - a21*b05 - a23*b03,
421 a12*b08 - a10*b11 - a13*b07,
422 a00*b11 - a02*b08 + a03*b07,
423 a32*b02 - a30*b05 - a33*b01,
424 a20*b05 - a22*b02 + a23*b01,
425 a10*b10 - a11*b08 + a13*b06,
426 a01*b08 - a00*b10 - a03*b06,
427 a30*b04 - a31*b02 + a33*b00,
428 a21*b02 - a20*b04 - a23*b00,
429 a11*b07 - a10*b09 - a12*b06,
430 a00*b09 - a01*b07 + a02*b06,
431 a31*b01 - a30*b03 - a32*b00,
432 a20*b03 - a21*b01 + a22*b00) * (1/det);
433}
434)";
435
John Stilesd7199b22020-12-30 16:22:58 -0500436String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
437 // Only use polyfills for a function taking a single-argument square matrix.
438 if (arguments.size() == 1) {
439 const Type& type = arguments.front()->type();
440 if (type.isMatrix() && type.rows() == type.columns()) {
441 // Inject the correct polyfill based on the matrix size.
442 String name = this->typeName(type) + "_inverse";
443 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
444 if (didInsert) {
445 switch (type.rows()) {
446 case 2:
447 fExtraFunctions.writeText(kInverse2x2);
448 break;
449 case 3:
450 fExtraFunctions.writeText(kInverse3x3);
451 break;
452 case 4:
453 fExtraFunctions.writeText(kInverse4x4);
454 break;
455 }
456 }
457 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500458 }
459 }
John Stilesd7199b22020-12-30 16:22:58 -0500460 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
461 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500462}
463
John Stilesfeb1e122021-09-09 14:27:28 -0400464void MetalCodeGenerator::writeMatrixCompMult() {
465 static constexpr char kMatrixCompMult[] = R"(
Brian Osman93aed9a2020-12-28 15:18:46 -0500466template <int C, int R>
467matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
468 matrix<float, C, R> result;
469 for (int c = 0; c < C; ++c) {
470 result[c] = a[c] * b[c];
471 }
472 return result;
473}
474)";
475
Brian Osman93aed9a2020-12-28 15:18:46 -0500476 String name = "matrixCompMult";
477 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
478 fWrittenIntrinsics.insert(name);
479 fExtraFunctions.writeText(kMatrixCompMult);
480 }
481}
482
John Stilesfeb1e122021-09-09 14:27:28 -0400483void MetalCodeGenerator::writeOuterProduct() {
484 static constexpr char kOuterProduct[] = R"(
485template <int C, int R>
486matrix<float, C, R> outerProduct(const vec<float, R> a, const vec<float, C> b) {
487 matrix<float, C, R> result;
488 for (int c = 0; c < C; ++c) {
489 result[c] = a * b[c];
490 }
491 return result;
492}
493)";
494
495 String name = "outerProduct";
496 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
497 fWrittenIntrinsics.insert(name);
498 fExtraFunctions.writeText(kOuterProduct);
499 }
500}
501
John Stiles86424eb2020-12-11 11:17:14 -0500502String MetalCodeGenerator::getTempVariable(const Type& type) {
503 String tempVar = "_skTemp" + to_string(fVarCount++);
504 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
505 return tempVar;
506}
507
John Stiles791c27d2020-12-30 14:56:57 -0500508void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
509 // Write out an intrinsic function call exactly as-is. No muss no fuss.
510 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500511 this->writeArgumentList(c.arguments());
512}
513
514void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500515 this->write("(");
516 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500517 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500518 this->write(separator);
519 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500520 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500521 }
522 this->write(")");
523}
524
John Stiles496b7d12021-05-06 10:26:45 -0400525bool MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400526 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400527 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400528 case k_sample_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500529 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400530 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500531 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400532 this->write(SAMPLER_SUFFIX);
533 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400534 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400535 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500536 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500537 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500538 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500539 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500540 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400541 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400542 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500543 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400544 this->write(")");
545 }
John Stiles496b7d12021-05-06 10:26:45 -0400546 return true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400547 }
John Stiles496b7d12021-05-06 10:26:45 -0400548 case k_mod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400549 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
John Stiles86424eb2020-12-11 11:17:14 -0500550 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500551 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500552 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500553 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500554 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500555 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500556 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
John Stiles496b7d12021-05-06 10:26:45 -0400557 return true;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500558 }
Brian Osman46787d52020-11-24 14:18:23 -0500559 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stiles496b7d12021-05-06 10:26:45 -0400560 case k_distance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500561 if (arguments[0]->type().columns() == 1) {
562 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500563 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500564 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500565 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500566 this->write(")");
567 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500568 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500569 }
John Stiles496b7d12021-05-06 10:26:45 -0400570 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500571 }
John Stiles496b7d12021-05-06 10:26:45 -0400572 case k_dot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500573 if (arguments[0]->type().columns() == 1) {
574 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500575 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500576 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500577 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500578 this->write(")");
579 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500580 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500581 }
John Stiles496b7d12021-05-06 10:26:45 -0400582 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500583 }
John Stiles496b7d12021-05-06 10:26:45 -0400584 case k_faceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500585 if (arguments[0]->type().columns() == 1) {
586 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
587 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500588 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500589 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500590 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500591 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500592 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500593 this->write("))");
594 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500595 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500596 }
John Stiles496b7d12021-05-06 10:26:45 -0400597 return true;
John Stilesad0571f2020-12-10 18:03:10 -0500598 }
John Stiles496b7d12021-05-06 10:26:45 -0400599 case k_length_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500600 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500601 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500602 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400603 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500604 }
John Stiles496b7d12021-05-06 10:26:45 -0400605 case k_normalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500606 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500607 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500608 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400609 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500610 }
John Stilesb6981fb2021-09-08 15:11:27 -0400611 case k_packUnorm2x16_IntrinsicKind: {
612 this->write("pack_float_to_unorm2x16(");
613 this->writeExpression(*arguments[0], Precedence::kSequence);
614 this->write(")");
615 return true;
616 }
617 case k_unpackUnorm2x16_IntrinsicKind: {
618 this->write("unpack_unorm2x16_to_float(");
619 this->writeExpression(*arguments[0], Precedence::kSequence);
620 this->write(")");
621 return true;
622 }
623 case k_packSnorm2x16_IntrinsicKind: {
624 this->write("pack_float_to_snorm2x16(");
625 this->writeExpression(*arguments[0], Precedence::kSequence);
626 this->write(")");
627 return true;
628 }
629 case k_unpackSnorm2x16_IntrinsicKind: {
630 this->write("unpack_snorm2x16_to_float(");
631 this->writeExpression(*arguments[0], Precedence::kSequence);
632 this->write(")");
633 return true;
634 }
635 case k_packUnorm4x8_IntrinsicKind: {
636 this->write("pack_float_to_unorm4x8(");
637 this->writeExpression(*arguments[0], Precedence::kSequence);
638 this->write(")");
639 return true;
640 }
641 case k_unpackUnorm4x8_IntrinsicKind: {
642 this->write("unpack_unorm4x8_to_float(");
643 this->writeExpression(*arguments[0], Precedence::kSequence);
644 this->write(")");
645 return true;
646 }
647 case k_packSnorm4x8_IntrinsicKind: {
648 this->write("pack_float_to_snorm4x8(");
649 this->writeExpression(*arguments[0], Precedence::kSequence);
650 this->write(")");
651 return true;
652 }
653 case k_unpackSnorm4x8_IntrinsicKind: {
654 this->write("unpack_snorm4x8_to_float(");
655 this->writeExpression(*arguments[0], Precedence::kSequence);
656 this->write(")");
657 return true;
658 }
659 case k_packHalf2x16_IntrinsicKind: {
660 this->write("as_type<uint>(half2(");
661 this->writeExpression(*arguments[0], Precedence::kSequence);
662 this->write("))");
663 return true;
664 }
665 case k_unpackHalf2x16_IntrinsicKind: {
666 this->write("float2(as_type<half2>(");
667 this->writeExpression(*arguments[0], Precedence::kSequence);
668 this->write("))");
669 return true;
670 }
John Stiles496b7d12021-05-06 10:26:45 -0400671 case k_floatBitsToInt_IntrinsicKind:
672 case k_floatBitsToUint_IntrinsicKind:
673 case k_intBitsToFloat_IntrinsicKind:
674 case k_uintBitsToFloat_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500675 this->write(this->getBitcastIntrinsic(c.type()));
676 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500677 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500678 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400679 return true;
John Stiles0063a9f2020-12-10 18:01:45 -0500680 }
John Stiles496b7d12021-05-06 10:26:45 -0400681 case k_degrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500682 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500683 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500684 this->write(") * 57.2957795)");
John Stiles496b7d12021-05-06 10:26:45 -0400685 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500686 }
John Stiles496b7d12021-05-06 10:26:45 -0400687 case k_radians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500688 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500689 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500690 this->write(") * 0.0174532925)");
John Stiles496b7d12021-05-06 10:26:45 -0400691 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500692 }
John Stiles496b7d12021-05-06 10:26:45 -0400693 case k_dFdx_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500694 this->write("dfdx");
695 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400696 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500697 }
John Stiles496b7d12021-05-06 10:26:45 -0400698 case k_dFdy_IntrinsicKind: {
Brian Salomond8d85b92021-07-07 09:41:17 -0400699 this->write(fRTFlipName + ".y*dfdy");
John Stilesd7199b22020-12-30 16:22:58 -0500700 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400701 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500702 }
John Stiles496b7d12021-05-06 10:26:45 -0400703 case k_inverse_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500704 this->write(this->getInversePolyfill(arguments));
705 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400706 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500707 }
John Stiles496b7d12021-05-06 10:26:45 -0400708 case k_inversesqrt_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500709 this->write("rsqrt");
710 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400711 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500712 }
John Stiles496b7d12021-05-06 10:26:45 -0400713 case k_atan_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500714 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
715 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400716 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500717 }
John Stiles496b7d12021-05-06 10:26:45 -0400718 case k_reflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500719 if (arguments[0]->type().columns() == 1) {
720 // We need to synthesize `I - 2 * N * I * N`.
721 String tmpI = this->getTempVariable(arguments[0]->type());
722 String tmpN = this->getTempVariable(arguments[1]->type());
723
724 // (_skTempI = ...
725 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500726 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500727
728 // , _skTempN = ...
729 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500730 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500731
732 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
733 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
734 } else {
735 this->writeSimpleIntrinsic(c);
736 }
John Stiles496b7d12021-05-06 10:26:45 -0400737 return true;
John Stiles791c27d2020-12-30 14:56:57 -0500738 }
John Stiles496b7d12021-05-06 10:26:45 -0400739 case k_refract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500740 if (arguments[0]->type().columns() == 1) {
741 // Metal does implement refract for vectors; rather than reimplementing refract from
742 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
743 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500744 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500745 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500746 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500747 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500748 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500749 this->write(").x)");
750 } else {
751 this->writeSimpleIntrinsic(c);
752 }
John Stiles496b7d12021-05-06 10:26:45 -0400753 return true;
John Stiles4b783d62020-12-30 14:58:07 -0500754 }
John Stiles496b7d12021-05-06 10:26:45 -0400755 case k_roundEven_IntrinsicKind: {
John Stiles23456532020-12-30 18:12:48 -0500756 this->write("rint");
757 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400758 return true;
John Stiles23456532020-12-30 18:12:48 -0500759 }
John Stiles496b7d12021-05-06 10:26:45 -0400760 case k_bitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500761 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500762 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500763 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400764 return true;
John Stilese7dc7cb2020-12-22 15:37:14 -0500765 }
John Stiles496b7d12021-05-06 10:26:45 -0400766 case k_findLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500767 // Create a temp variable to store the expression, to avoid double-evaluating it.
768 String skTemp = this->getTempVariable(arguments[0]->type());
769 String exprType = this->typeName(arguments[0]->type());
770
771 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
772 // Use select to detect zero inputs and force a -1 result.
773
774 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
775 this->write("(");
776 this->write(skTemp);
777 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500778 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500779 this->write("), select(ctz(");
780 this->write(skTemp);
781 this->write("), ");
782 this->write(exprType);
783 this->write("(-1), ");
784 this->write(skTemp);
785 this->write(" == ");
786 this->write(exprType);
787 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400788 return true;
John Stiles86424eb2020-12-11 11:17:14 -0500789 }
John Stiles496b7d12021-05-06 10:26:45 -0400790 case k_findMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500791 // Create a temp variable to store the expression, to avoid double-evaluating it.
792 String skTemp1 = this->getTempVariable(arguments[0]->type());
793 String exprType = this->typeName(arguments[0]->type());
794
795 // GLSL findMSB is actually quite different from Metal's clz:
796 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
797 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
798
799 // (_skTemp1 = (.....),
800 this->write("(");
801 this->write(skTemp1);
802 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500803 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500804 this->write("), ");
805
806 // Signed input types might be negative; we need another helper variable to negate the
807 // input (since we can only find one bits, not zero bits).
808 String skTemp2;
809 if (arguments[0]->type().isSigned()) {
810 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
811 skTemp2 = this->getTempVariable(arguments[0]->type());
812 this->write(skTemp2);
813 this->write(" = (select(");
814 this->write(skTemp1);
815 this->write(", ~");
816 this->write(skTemp1);
817 this->write(", ");
818 this->write(skTemp1);
819 this->write(" < 0)), ");
820 } else {
821 skTemp2 = skTemp1;
822 }
823
824 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
825 this->write("select(");
826 this->write(this->typeName(c.type()));
827 this->write("(clz(");
828 this->write(skTemp2);
829 this->write(")), ");
830 this->write(this->typeName(c.type()));
831 this->write("(-1), ");
832 this->write(skTemp2);
833 this->write(" == ");
834 this->write(exprType);
835 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400836 return true;
John Stiles9685e522020-12-14 11:52:14 -0500837 }
John Stiles496b7d12021-05-06 10:26:45 -0400838 case k_matrixCompMult_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500839 this->writeMatrixCompMult();
840 this->writeSimpleIntrinsic(c);
John Stiles496b7d12021-05-06 10:26:45 -0400841 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500842 }
John Stilesfeb1e122021-09-09 14:27:28 -0400843 case k_outerProduct_IntrinsicKind: {
844 this->writeOuterProduct();
845 this->writeSimpleIntrinsic(c);
846 return true;
847 }
John Stilescc2d9cc2021-07-09 17:38:41 -0400848 case k_mix_IntrinsicKind: {
849 SkASSERT(c.arguments().size() == 3);
850 if (arguments[2]->type().componentType().isBoolean()) {
851 // The Boolean forms of GLSL mix() use the select() intrinsic in Metal.
852 this->write("select");
853 this->writeArgumentList(c.arguments());
854 return true;
855 }
856 // The basic form of mix() is supported by Metal as-is.
857 this->writeSimpleIntrinsic(c);
858 return true;
859 }
John Stiles496b7d12021-05-06 10:26:45 -0400860 case k_equal_IntrinsicKind:
861 case k_greaterThan_IntrinsicKind:
862 case k_greaterThanEqual_IntrinsicKind:
863 case k_lessThan_IntrinsicKind:
864 case k_lessThanEqual_IntrinsicKind:
865 case k_notEqual_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500866 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500867 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500868 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400869 case k_equal_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500870 this->write(" == ");
871 break;
John Stiles496b7d12021-05-06 10:26:45 -0400872 case k_notEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500873 this->write(" != ");
874 break;
John Stiles496b7d12021-05-06 10:26:45 -0400875 case k_lessThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500876 this->write(" < ");
877 break;
John Stiles496b7d12021-05-06 10:26:45 -0400878 case k_lessThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500879 this->write(" <= ");
880 break;
John Stiles496b7d12021-05-06 10:26:45 -0400881 case k_greaterThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500882 this->write(" > ");
883 break;
John Stiles496b7d12021-05-06 10:26:45 -0400884 case k_greaterThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500885 this->write(" >= ");
886 break;
887 default:
John Stilesf57207b2021-02-02 17:50:34 -0500888 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500889 }
Brian Osman00185012021-02-04 16:07:11 -0500890 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500891 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400892 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500893 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400894 default:
John Stiles496b7d12021-05-06 10:26:45 -0400895 return false;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400896 }
897}
898
John Stilesfcf8cb22020-08-06 14:29:22 -0400899// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
900// Cells that don't exist in the source matrix will be populated with identity-matrix values.
901void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
902 SkASSERT(rows <= 4);
903 SkASSERT(columns <= 4);
904
John Stilesc18ee4e2021-08-13 17:53:49 -0400905 std::string matrixType = this->typeName(sourceMatrix.componentType());
906
907 const char* separator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400908 for (int c = 0; c < columns; ++c) {
John Stilesc18ee4e2021-08-13 17:53:49 -0400909 fExtraFunctions.printf("%s%s%d(", separator, matrixType.c_str(), rows);
910 separator = "), ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400911
912 // Determine how many values to take from the source matrix for this row.
913 int swizzleLength = 0;
914 if (c < sourceMatrix.columns()) {
915 swizzleLength = std::min<>(rows, sourceMatrix.rows());
916 }
917
918 // Emit all the values from the source matrix row.
919 bool firstItem;
920 switch (swizzleLength) {
921 case 0: firstItem = true; break;
922 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
923 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
924 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
925 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
926 default: SkUNREACHABLE;
927 }
928
929 // Emit the placeholder identity-matrix cells.
930 for (int r = swizzleLength; r < rows; ++r) {
931 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
932 firstItem = false;
933 }
934 }
935
936 fExtraFunctions.writeText(")");
937}
938
John Stiles1f7300b2021-07-08 15:40:38 -0400939// Assembles a matrix of type floatCxR by concatenating an arbitrary mix of values, named `x0`,
940// `x1`, etc. An error is written if the expression list don't contain exactly C*R scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400941void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles1f7300b2021-07-08 15:40:38 -0400942 int columns, int rows) {
John Stilesc18ee4e2021-08-13 17:53:49 -0400943 SkASSERT(rows <= 4);
944 SkASSERT(columns <= 4);
945
946 std::string matrixType = this->typeName(ctor.type().componentType());
John Stilesfcf8cb22020-08-06 14:29:22 -0400947 size_t argIndex = 0;
948 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400949 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400950
John Stilesc18ee4e2021-08-13 17:53:49 -0400951 const char* separator = "";
John Stiles143e8502021-09-14 12:04:11 -0400952 for (int c = 0; c < columns; ++c) {
John Stilesc18ee4e2021-08-13 17:53:49 -0400953 fExtraFunctions.printf("%s%s%d(", separator, matrixType.c_str(), rows);
954 separator = "), ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400955
John Stiles1f7300b2021-07-08 15:40:38 -0400956 const char* columnSeparator = "";
John Stiles143e8502021-09-14 12:04:11 -0400957 for (int r = 0; r < rows; ++r) {
John Stiles1f7300b2021-07-08 15:40:38 -0400958 fExtraFunctions.writeText(columnSeparator);
959 columnSeparator = ", ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400960
961 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400962 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400963 switch (argType.typeKind()) {
964 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400965 fExtraFunctions.printf("x%zu", argIndex);
966 break;
967 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400968 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400969 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
970 break;
971 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400972 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400973 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
974 argPosition / argType.rows(),
975 argPosition % argType.rows());
976 break;
977 }
978 default: {
979 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
980 fExtraFunctions.writeText("<error>");
981 break;
982 }
983 }
984
985 ++argPosition;
986 if (argPosition >= argType.columns() * argType.rows()) {
987 ++argIndex;
988 argPosition = 0;
989 }
990 } else {
991 SkDEBUGFAIL("not enough arguments for matrix constructor");
992 fExtraFunctions.writeText("<error>");
993 }
994 }
995 }
996
997 if (argPosition != 0 || argIndex != args.size()) {
998 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
999 fExtraFunctions.writeText(", <error>");
1000 }
1001
1002 fExtraFunctions.writeText(")");
1003}
1004
John Stiles1bdafbf2020-05-28 12:17:20 -04001005// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
1006// Keeps track of previously generated constructors so that we won't generate more than one
1007// constructor for any given permutation of input argument types. Returns the name of the
1008// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -04001009String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
John Stilesc18ee4e2021-08-13 17:53:49 -04001010 const Type& type = c.type();
1011 int columns = type.columns();
1012 int rows = type.rows();
John Stiles5abb9e12021-04-06 13:47:19 -04001013 auto args = c.argumentSpan();
John Stilesc18ee4e2021-08-13 17:53:49 -04001014 String typeName = this->typeName(type);
John Stiles1bdafbf2020-05-28 12:17:20 -04001015
1016 // Create the helper-method name and use it as our lookup key.
1017 String name;
John Stilesc18ee4e2021-08-13 17:53:49 -04001018 name.appendf("%s_from", typeName.c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -04001019 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -05001020 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -04001021 }
1022
1023 // If a helper-method has already been synthesized, we don't need to synthesize it again.
1024 auto [iter, newlyCreated] = fHelpers.insert(name);
1025 if (!newlyCreated) {
1026 return name;
1027 }
1028
1029 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
1030 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
1031 // supply a mixture of scalars and vectors.)
John Stilesc18ee4e2021-08-13 17:53:49 -04001032 fExtraFunctions.printf("%s %s(", typeName.c_str(), name.c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -04001033
1034 size_t argIndex = 0;
1035 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -04001036 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001037 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -05001038 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -04001039 argSeparator = ", ";
1040 }
1041
John Stilesc18ee4e2021-08-13 17:53:49 -04001042 fExtraFunctions.printf(") {\n return %s(", typeName.c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -04001043
John Stiles9aeed132020-11-24 17:36:06 -05001044 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001045 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -04001046 } else {
John Stiles1f7300b2021-07-08 15:40:38 -04001047 this->assembleMatrixFromExpressions(c, columns, rows);
John Stiles1bdafbf2020-05-28 12:17:20 -04001048 }
1049
John Stilesfcf8cb22020-08-06 14:29:22 -04001050 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001051 return name;
1052}
1053
1054bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
1055 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
1056 return false;
1057 }
1058 if (t1.columns() > 1) {
1059 return this->canCoerce(t1.componentType(), t2.componentType());
1060 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001061 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001062}
1063
John Stiles8cad6372021-04-07 12:31:13 -04001064bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001065 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -04001066
1067 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1068 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1069 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1070 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1071 // that converts our inputs into a properly-shaped matrix.
1072 // A matrix construct helper method is always used if any input argument is a matrix.
1073 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1074 //
1075 // float2 x = (1, 2);
1076 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1077 // | 2 4 6 |
1078 //
1079 // float2 x = (2, 3);
1080 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1081 // | 2 4 6 |
1082 //
1083 // float4 x = (1, 2, 3, 4);
1084 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1085 // | 2 4 |
1086 //
1087
1088 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001089 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001090 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001091 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001092 return true;
1093 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001094 position += expr->type().columns();
1095 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001096 // An input argument would span multiple rows; a helper function is required.
1097 return true;
1098 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001099 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001100 // We've advanced to the end of a row. Wrap to the start of the next row.
1101 position = 0;
1102 }
1103 }
1104
1105 return false;
1106}
1107
John Stiles5abb9e12021-04-06 13:47:19 -04001108void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1109 Precedence parentPrecedence) {
1110 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1111 // matrix-construct helper here.
1112 this->write(this->getMatrixConstructHelper(c));
1113 this->write("(");
1114 this->writeExpression(*c.argument(), Precedence::kSequence);
1115 this->write(")");
1116}
1117
John Stiles8cad6372021-04-07 12:31:13 -04001118void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1119 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001120 if (c.type().isVector()) {
1121 this->writeConstructorCompoundVector(c, parentPrecedence);
1122 } else if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001123 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001124 } else {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001125 fContext.fErrors->error(c.fOffset, "unsupported compound constructor");
John Stiles2bec8ab2021-04-06 18:40:04 -04001126 }
1127}
John Stiles7384b372021-04-01 13:48:15 -04001128
John Stilesc18ee4e2021-08-13 17:53:49 -04001129String MetalCodeGenerator::getVectorFromMat2x2ConstructorHelper(const Type& matrixType) {
1130 SkASSERT(matrixType.isMatrix());
1131 SkASSERT(matrixType.rows() == 2);
1132 SkASSERT(matrixType.columns() == 2);
John Stiles6de2e1d2021-07-09 12:41:55 -04001133
John Stilesc18ee4e2021-08-13 17:53:49 -04001134 String baseType = this->typeName(matrixType.componentType());
1135 String name = String::printf("%s4_from_%s2x2", baseType.c_str(), baseType.c_str());
1136 if (fHelpers.find(name) == fHelpers.end()) {
1137 fHelpers.insert(name);
1138
1139 fExtraFunctions.printf(R"(
1140%s4 %s(%s2x2 x) {
1141 return %s4(x[0].xy, x[1].xy);
1142}
1143)", baseType.c_str(), name.c_str(), baseType.c_str(), baseType.c_str());
John Stiles6de2e1d2021-07-09 12:41:55 -04001144 }
John Stilesc18ee4e2021-08-13 17:53:49 -04001145
1146 return name;
John Stiles6de2e1d2021-07-09 12:41:55 -04001147}
1148
1149void MetalCodeGenerator::writeConstructorCompoundVector(const ConstructorCompound& c,
1150 Precedence parentPrecedence) {
1151 SkASSERT(c.type().isVector());
1152
1153 // Metal supports constructing vectors from a mix of scalars and vectors, but not matrices.
1154 // GLSL supports vec4(mat2x2), so we detect that case here and emit a helper function.
1155 if (c.type().columns() == 4 && c.argumentSpan().size() == 1) {
1156 const Expression& expr = *c.argumentSpan().front();
1157 if (expr.type().isMatrix()) {
John Stilesc18ee4e2021-08-13 17:53:49 -04001158 this->write(this->getVectorFromMat2x2ConstructorHelper(expr.type()));
1159 this->write("(");
John Stiles6de2e1d2021-07-09 12:41:55 -04001160 this->writeExpression(expr, Precedence::kSequence);
1161 this->write(")");
1162 return;
1163 }
1164 }
1165
1166 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1167}
1168
John Stiles8cad6372021-04-07 12:31:13 -04001169void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1170 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001171 SkASSERT(c.type().isMatrix());
1172
John Stiles1bdafbf2020-05-28 12:17:20 -04001173 // Emit and invoke a matrix-constructor helper method if one is necessary.
1174 if (this->matrixConstructHelperIsNeeded(c)) {
1175 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001176 this->write("(");
1177 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001178 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001179 this->write(separator);
1180 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001181 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001182 }
John Stiles1fa15b12020-05-28 17:36:54 +00001183 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001184 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001185 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001186
John Stiles2bec8ab2021-04-06 18:40:04 -04001187 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1188 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1189 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1190 // can group our inputs up and synthesize a constructor for each column.
1191 const Type& matrixType = c.type();
1192 const Type& columnType = matrixType.componentType().toCompound(
1193 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1194
1195 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001196 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001197 const char* separator = "";
1198 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001199 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001200 this->write(separator);
1201 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001202 if (arg->type().columns() < matrixType.rows()) {
1203 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001204 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001205 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001206 this->write("(");
1207 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001208 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001209 }
Brian Osman00185012021-02-04 16:07:11 -05001210 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001211 if (scalarCount && scalarCount == matrixType.rows()) {
1212 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001213 this->write(")");
1214 scalarCount = 0;
1215 }
1216 }
John Stiles7384b372021-04-01 13:48:15 -04001217 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001218}
1219
John Stilesb14a8192021-04-05 11:40:46 -04001220void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1221 const char* leftBracket,
1222 const char* rightBracket,
1223 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001224 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001225 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001226 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001227 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001228 this->write(separator);
1229 separator = ", ";
1230 this->writeExpression(*arg, Precedence::kSequence);
1231 }
John Stilesb14a8192021-04-05 11:40:46 -04001232 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001233}
1234
John Stilesb14a8192021-04-05 11:40:46 -04001235void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1236 const char* leftBracket,
1237 const char* rightBracket,
1238 Precedence parentPrecedence) {
1239 // If the type is coercible, emit it directly without the cast.
1240 auto args = c.argumentSpan();
1241 if (args.size() == 1) {
1242 if (this->canCoerce(c.type(), args.front()->type())) {
1243 this->writeExpression(*args.front(), parentPrecedence);
1244 return;
1245 }
John Stilesfd7252f2021-04-04 22:24:40 -04001246 }
1247
John Stilesb14a8192021-04-05 11:40:46 -04001248 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001249}
1250
Ethan Nicholascc305772017-10-13 16:17:45 -04001251void MetalCodeGenerator::writeFragCoord() {
Brian Salomond8d85b92021-07-07 09:41:17 -04001252 SkASSERT(fRTFlipName.length());
1253 this->write("float4(_fragCoord.x, ");
1254 this->write(fRTFlipName.c_str());
1255 this->write(".x + ");
1256 this->write(fRTFlipName.c_str());
1257 this->write(".y * _fragCoord.y, 0.0, _fragCoord.w)");
Ethan Nicholascc305772017-10-13 16:17:45 -04001258}
1259
1260void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001261 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001262 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001263 // we're actually targeting the clones.
1264 if (fIgnoreVariableReferenceModifiers) {
1265 this->writeName(ref.variable()->name());
1266 return;
1267 }
1268
Ethan Nicholas78686922020-10-08 06:46:27 -04001269 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001270 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001271 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001272 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001273 case SK_FRAGCOORD_BUILTIN:
1274 this->writeFragCoord();
1275 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001276 case SK_VERTEXID_BUILTIN:
1277 this->write("sk_VertexID");
1278 break;
1279 case SK_INSTANCEID_BUILTIN:
1280 this->write("sk_InstanceID");
1281 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001282 case SK_CLOCKWISE_BUILTIN:
1283 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001284 // clockwise to match Skia convention.
Brian Salomond8d85b92021-07-07 09:41:17 -04001285 this->write("(" + fRTFlipName + ".y < 0 ? _frontFacing : !_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001286 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001287 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001288 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001289 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001290 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001291 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001292 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001293 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001294 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1295 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001296 this->write("_uniforms.");
1297 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001298 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001299 }
1300 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001301 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001302 }
1303}
1304
1305void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001306 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001307 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001308 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001309 this->write("]");
1310}
1311
1312void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001313 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1314 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001315 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001316 this->write(".");
1317 }
Timothy Liang7d637782018-06-05 09:58:07 -04001318 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001319 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001320 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001321 break;
1322 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001323 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001324 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001325 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001326 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001327 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001328 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1329 this->write("->");
1330 }
Timothy Liang651286f2018-06-07 09:55:33 -04001331 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001332 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001333 }
1334}
1335
1336void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001337 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001338 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001339 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001340 SkASSERT(c >= 0 && c <= 3);
1341 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001342 }
1343}
1344
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001345void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1346 const Type& result) {
John Stilesc985e142021-05-13 14:01:48 -04001347 SkASSERT(left.isMatrix());
1348 SkASSERT(right.isMatrix());
1349 SkASSERT(result.isMatrix());
1350 SkASSERT(left.rows() == right.rows());
1351 SkASSERT(left.columns() == right.columns());
1352 SkASSERT(left.rows() == result.rows());
1353 SkASSERT(left.columns() == result.columns());
1354
1355 String key = "Matrix *= " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001356
1357 auto [iter, wasInserted] = fHelpers.insert(key);
1358 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001359 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001360 " left = left * right;\n"
1361 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001362 "}\n",
1363 this->typeName(result).c_str(), this->typeName(left).c_str(),
1364 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001365 }
1366}
1367
John Stiles39346472021-04-29 14:39:35 -04001368void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1369 SkASSERT(left.isMatrix());
1370 SkASSERT(right.isMatrix());
1371 SkASSERT(left.rows() == right.rows());
1372 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001373
John Stilesc985e142021-05-13 14:01:48 -04001374 String key = "Matrix == " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001375
1376 auto [iter, wasInserted] = fHelpers.insert(key);
1377 if (wasInserted) {
John Stiles82d4c122021-08-10 16:03:23 -04001378 fExtraFunctionPrototypes.printf(R"(
1379thread bool operator==(const %s left, const %s right);
1380thread bool operator!=(const %s left, const %s right);
1381)",
1382 this->typeName(left).c_str(),
1383 this->typeName(right).c_str(),
1384 this->typeName(left).c_str(),
1385 this->typeName(right).c_str());
1386
John Stiles01cdf012021-02-10 09:53:41 -05001387 fExtraFunctions.printf(
1388 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001389 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001390 this->typeName(left).c_str(), this->typeName(right).c_str());
1391
John Stiles39346472021-04-29 14:39:35 -04001392 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001393 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001394 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1395 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001396 }
John Stiles39346472021-04-29 14:39:35 -04001397
1398 fExtraFunctions.printf(
1399 ";\n"
1400 "}\n"
1401 "thread bool operator!=(const %s left, const %s right) {\n"
1402 " return !(left == right);\n"
1403 "}\n",
1404 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001405 }
1406}
1407
John Stilesc985e142021-05-13 14:01:48 -04001408void MetalCodeGenerator::writeMatrixDivisionHelpers(const Type& type) {
1409 SkASSERT(type.isMatrix());
1410
1411 String key = "Matrix / " + this->typeName(type);
1412
1413 auto [iter, wasInserted] = fHelpers.insert(key);
1414 if (wasInserted) {
1415 String typeName = this->typeName(type);
1416
1417 fExtraFunctions.printf(
1418 "thread %s operator/(const %s left, const %s right) {\n"
1419 " return %s(",
1420 typeName.c_str(), typeName.c_str(), typeName.c_str(), typeName.c_str());
1421
1422 const char* separator = "";
1423 for (int index=0; index<type.columns(); ++index) {
1424 fExtraFunctions.printf("%sleft[%d] / right[%d]", separator, index, index);
1425 separator = ", ";
1426 }
1427
1428 fExtraFunctions.printf(");\n"
1429 "}\n"
1430 "thread %s& operator/=(thread %s& left, thread const %s& right) {\n"
1431 " left = left / right;\n"
1432 " return left;\n"
1433 "}\n",
1434 typeName.c_str(), typeName.c_str(), typeName.c_str());
1435 }
1436}
1437
John Stiles39346472021-04-29 14:39:35 -04001438void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1439 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001440
John Stiles39346472021-04-29 14:39:35 -04001441 // If the array's component type needs a helper as well, we need to emit that one first.
1442 this->writeEqualityHelpers(type.componentType(), type.componentType());
1443
1444 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1445 if (wasInserted) {
John Stiles82d4c122021-08-10 16:03:23 -04001446 fExtraFunctionPrototypes.writeText(R"(
1447template <typename T1, typename T2, size_t N>
1448bool operator==(thread const array<T1, N>& left, thread const array<T2, N>& right);
1449template <typename T1, typename T2, size_t N>
1450bool operator!=(thread const array<T1, N>& left, thread const array<T2, N>& right);
1451)");
John Stiles39346472021-04-29 14:39:35 -04001452 fExtraFunctions.writeText(R"(
John Stilese3ae9682021-08-05 10:35:01 -04001453template <typename T1, typename T2, size_t N>
1454bool operator==(thread const array<T1, N>& left, thread const array<T2, N>& right) {
John Stiles39346472021-04-29 14:39:35 -04001455 for (size_t index = 0; index < N; ++index) {
John Stilese076c382021-08-10 16:56:23 +00001456 if (!all(left[index] == right[index])) {
John Stiles39346472021-04-29 14:39:35 -04001457 return false;
1458 }
1459 }
1460 return true;
1461}
1462
John Stilese3ae9682021-08-05 10:35:01 -04001463template <typename T1, typename T2, size_t N>
1464bool operator!=(thread const array<T1, N>& left, thread const array<T2, N>& right) {
John Stiles39346472021-04-29 14:39:35 -04001465 return !(left == right);
1466}
1467)");
1468 }
1469}
1470
1471void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1472 SkASSERT(type.isStruct());
1473 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001474
1475 auto [iter, wasInserted] = fHelpers.insert(key);
1476 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001477 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1478 for (const Type::Field& field : type.fields()) {
1479 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001480 }
John Stiles39346472021-04-29 14:39:35 -04001481
1482 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1483 // and GLSL but do not exist by default in Metal.
John Stiles82d4c122021-08-10 16:03:23 -04001484 fExtraFunctionPrototypes.printf(R"(
1485thread bool operator==(thread const %s& left, thread const %s& right);
1486thread bool operator!=(thread const %s& left, thread const %s& right);
1487)",
1488 this->typeName(type).c_str(),
1489 this->typeName(type).c_str(),
1490 this->typeName(type).c_str(),
1491 this->typeName(type).c_str());
1492
John Stiles39346472021-04-29 14:39:35 -04001493 fExtraFunctions.printf(
1494 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1495 " return ",
1496 this->typeName(type).c_str(),
1497 this->typeName(type).c_str());
1498
1499 const char* separator = "";
1500 for (const Type::Field& field : type.fields()) {
1501 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1502 separator,
1503 (int)field.fName.size(), field.fName.data(),
1504 (int)field.fName.size(), field.fName.data());
1505 separator = " &&\n ";
1506 }
1507 fExtraFunctions.printf(
1508 ";\n"
1509 "}\n"
1510 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1511 " return !(left == right);\n"
1512 "}\n",
1513 this->typeName(type).c_str(),
1514 this->typeName(type).c_str());
1515 }
1516}
1517
1518void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1519 if (leftType.isArray() && rightType.isArray()) {
1520 this->writeArrayEqualityHelpers(leftType);
1521 return;
1522 }
1523 if (leftType.isStruct() && rightType.isStruct()) {
1524 this->writeStructEqualityHelpers(leftType);
1525 return;
1526 }
1527 if (leftType.isMatrix() && rightType.isMatrix()) {
1528 this->writeMatrixEqualityHelpers(leftType, rightType);
1529 return;
John Stiles01cdf012021-02-10 09:53:41 -05001530 }
1531}
1532
John Stiles6b131292021-05-12 17:12:21 -04001533void MetalCodeGenerator::writeNumberAsMatrix(const Expression& expr, const Type& matrixType) {
1534 SkASSERT(expr.type().isNumber());
1535 SkASSERT(matrixType.isMatrix());
1536
1537 // Componentwise multiply the scalar against a matrix of the desired size which contains all 1s.
1538 this->write("(");
1539 this->writeType(matrixType);
1540 this->write("(");
1541
1542 const char* separator = "";
1543 for (int index = matrixType.slotCount(); index--;) {
1544 this->write(separator);
1545 this->write("1.0");
1546 separator = ", ";
1547 }
1548
1549 this->write(") * ");
1550 this->writeExpression(expr, Precedence::kMultiplicative);
1551 this->write(")");
1552}
1553
Ethan Nicholascc305772017-10-13 16:17:45 -04001554void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1555 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001556 const Expression& left = *b.left();
1557 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001558 const Type& leftType = left.type();
1559 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001560 Operator op = b.getOperator();
1561 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001562 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001563 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001564 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001565 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001566 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001567 this->write("all");
1568 needParens = true;
1569 }
1570 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001571 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001572 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001573 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001574 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001575 needParens = true;
1576 }
1577 break;
1578 default:
1579 break;
1580 }
John Stiles39346472021-04-29 14:39:35 -04001581 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1582 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001583 }
John Stilesc985e142021-05-13 14:01:48 -04001584 if (op.removeAssignment().kind() == Token::Kind::TK_SLASH &&
1585 ((leftType.isMatrix() && rightType.isMatrix()) ||
1586 (leftType.isScalar() && rightType.isMatrix()) ||
1587 (leftType.isMatrix() && rightType.isScalar()))) {
1588 this->writeMatrixDivisionHelpers(leftType.isMatrix() ? leftType : rightType);
1589 }
1590 if (needParens) {
1591 this->write("(");
1592 }
John Stiles6011bbc2021-05-19 22:56:18 -04001593 bool needMatrixSplatOnScalar = rightType.isMatrix() && leftType.isNumber() &&
1594 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001595 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1596 if (needMatrixSplatOnScalar) {
1597 this->writeNumberAsMatrix(left, rightType);
1598 } else {
1599 this->writeExpression(left, precedence);
1600 }
John Stiles45990502021-02-16 10:55:27 -05001601 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001602 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001603 // This doesn't compile in Metal:
1604 // float4 x = float4(1);
1605 // x.xy *= float2x2(...);
1606 // with the error message "non-const reference cannot bind to vector element",
1607 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1608 // as long as the LHS has no side effects, and hope for the best otherwise.
1609 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001610 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001611 this->write(" ");
John Stiles7cbe66b2021-05-12 17:01:23 -04001612 this->write(OperatorName(op.removeAssignment()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001613 this->write(" ");
1614 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001615 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001616 }
John Stiles6b131292021-05-12 17:12:21 -04001617
John Stiles6011bbc2021-05-19 22:56:18 -04001618 needMatrixSplatOnScalar = leftType.isMatrix() && rightType.isNumber() &&
1619 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001620 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1621 if (needMatrixSplatOnScalar) {
1622 this->writeNumberAsMatrix(right, leftType);
1623 } else {
1624 this->writeExpression(right, precedence);
1625 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001626 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001627 this->write(")");
1628 }
1629}
1630
1631void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1632 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001633 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001634 this->write("(");
1635 }
Brian Osman00185012021-02-04 16:07:11 -05001636 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001637 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001638 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001639 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001640 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1641 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001642 this->write(")");
1643 }
1644}
1645
1646void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1647 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001648 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001649 this->write("(");
1650 }
John Stilesd6449e92020-11-30 09:13:23 -05001651 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001652 this->writeExpression(*p.operand(), Precedence::kPrefix);
1653 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001654 this->write(")");
1655 }
1656}
1657
1658void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1659 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001660 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001661 this->write("(");
1662 }
Brian Osman00185012021-02-04 16:07:11 -05001663 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001664 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001665 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001666 this->write(")");
1667 }
1668}
1669
John Stiles7591d4b2021-09-13 13:32:06 -04001670void MetalCodeGenerator::writeLiteral(const Literal& l) {
1671 const Type& type = l.type();
1672 if (type.isFloat()) {
1673 this->write(to_string(l.floatValue()));
1674 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001675 }
John Stiles7591d4b2021-09-13 13:32:06 -04001676 if (type.isInteger()) {
1677 if (type == *fContext.fTypes.fUInt) {
1678 this->write(to_string(l.intValue() & 0xffffffff) + "u");
1679 } else if (type == *fContext.fTypes.fUShort) {
1680 this->write(to_string(l.intValue() & 0xffff) + "u");
1681 } else {
1682 this->write(to_string(l.intValue()));
1683 }
1684 return;
1685 }
1686 SkASSERT(type.isBoolean());
1687 this->write(l.boolValue() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001688}
1689
1690void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001691 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001692}
1693
John Stiles06b84ef2020-12-09 12:35:48 -05001694void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1695 const char*& separator) {
1696 Requirements requirements = this->requirements(f);
1697 if (requirements & kInputs_Requirement) {
1698 this->write(separator);
1699 this->write("_in");
1700 separator = ", ";
1701 }
1702 if (requirements & kOutputs_Requirement) {
1703 this->write(separator);
1704 this->write("_out");
1705 separator = ", ";
1706 }
1707 if (requirements & kUniforms_Requirement) {
1708 this->write(separator);
1709 this->write("_uniforms");
1710 separator = ", ";
1711 }
1712 if (requirements & kGlobals_Requirement) {
1713 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001714 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001715 separator = ", ";
1716 }
1717 if (requirements & kFragCoord_Requirement) {
1718 this->write(separator);
1719 this->write("_fragCoord");
1720 separator = ", ";
1721 }
1722}
1723
1724void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1725 const char*& separator) {
1726 Requirements requirements = this->requirements(f);
1727 if (requirements & kInputs_Requirement) {
1728 this->write(separator);
1729 this->write("Inputs _in");
1730 separator = ", ";
1731 }
1732 if (requirements & kOutputs_Requirement) {
1733 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001734 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001735 separator = ", ";
1736 }
1737 if (requirements & kUniforms_Requirement) {
1738 this->write(separator);
1739 this->write("Uniforms _uniforms");
1740 separator = ", ";
1741 }
1742 if (requirements & kGlobals_Requirement) {
1743 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001744 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001745 separator = ", ";
1746 }
1747 if (requirements & kFragCoord_Requirement) {
1748 this->write(separator);
1749 this->write("float4 _fragCoord");
1750 separator = ", ";
1751 }
1752}
1753
John Stilesda5cdf62021-01-28 11:47:29 -05001754int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1755 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001756 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001757}
1758
1759int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1760 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001761 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001762}
1763
John Stiles569249b2020-11-03 12:18:22 -05001764bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001765 fRTFlipName = fProgram.fInputs.fUseFlipRTUniform
1766 ? "_globals._anonInterface0->" SKSL_RTFLIP_NAME
1767 : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001768 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001769 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001770 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001771 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001772 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001773 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001774 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001775 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001776 break;
1777 default:
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001778 fContext.fErrors->error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001779 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001780 }
1781 this->write("(Inputs _in [[stage_in]]");
1782 if (-1 != fUniformBuffer) {
1783 this->write(", constant Uniforms& _uniforms [[buffer(" +
1784 to_string(fUniformBuffer) + ")]]");
1785 }
Brian Osman133724c2020-10-28 14:14:39 -04001786 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001787 if (e->is<GlobalVarDeclaration>()) {
1788 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001789 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1790 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1791 if (var.var().modifiers().fLayout.fBinding < 0) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001792 fContext.fErrors->error(decls.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001793 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001794 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001795 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001796 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001797 // Not yet implemented--Skia currently only uses 2D textures.
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001798 fContext.fErrors->error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001799 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001800 }
1801 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001802 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001803 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001804 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001805 this->write(")]]");
1806 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001807 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001808 this->write(SAMPLER_SUFFIX);
1809 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001810 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001811 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001812 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001813 } else if (e->is<InterfaceBlock>()) {
1814 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001815 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001816 continue;
1817 }
1818 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001819 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001820 this->write("& " );
1821 this->write(fInterfaceBlockNameMap[&intf]);
1822 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001823 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001824 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001825 }
1826 }
John Stiles270cec22021-02-17 12:59:36 -05001827 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001828 if (fProgram.fInputs.fUseFlipRTUniform && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001829 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Brian Salomond8d85b92021-07-07 09:41:17 -04001830 fRTFlipName = "_anonInterface0." SKSL_RTFLIP_NAME;
Timothy Liang5422f9a2018-08-10 10:57:55 -04001831 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001832 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001833 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001834 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001835 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001836 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001837 separator = ", ";
1838 } else {
John Stilesb4418502021-02-04 10:57:08 -05001839 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001840 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001841 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001842 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001843 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001844 }
John Stiles569249b2020-11-03 12:18:22 -05001845 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001846 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1847 continue;
1848 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001849 this->write(separator);
1850 separator = ", ";
Brian Osman58134e12021-05-13 14:51:07 -04001851 this->writeModifiers(param->modifiers());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001852 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001853 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001854 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001855 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001856 }
Timothy Liang651286f2018-06-07 09:55:33 -04001857 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001858 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001859 }
John Stiles569249b2020-11-03 12:18:22 -05001860 this->write(")");
1861 return true;
1862}
Ethan Nicholascc305772017-10-13 16:17:45 -04001863
John Stiles569249b2020-11-03 12:18:22 -05001864void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1865 this->writeFunctionDeclaration(f.declaration());
1866 this->writeLine(";");
1867}
1868
John Stiles986c7fb2020-12-01 14:44:56 -05001869static bool is_block_ending_with_return(const Statement* stmt) {
1870 // This function detects (potentially nested) blocks that end in a return statement.
1871 if (!stmt->is<Block>()) {
1872 return false;
1873 }
1874 const StatementArray& block = stmt->as<Block>().children();
1875 for (int index = block.count(); index--; ) {
John Stiles628777c2021-08-04 22:07:41 -04001876 stmt = block[index].get();
1877 if (stmt->is<ReturnStatement>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001878 return true;
1879 }
John Stiles628777c2021-08-04 22:07:41 -04001880 if (stmt->is<Block>()) {
1881 return is_block_ending_with_return(stmt);
John Stiles986c7fb2020-12-01 14:44:56 -05001882 }
John Stiles628777c2021-08-04 22:07:41 -04001883 if (!stmt->is<Nop>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001884 break;
1885 }
1886 }
1887 return false;
1888}
1889
John Stiles569249b2020-11-03 12:18:22 -05001890void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001891 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001892
John Stiles569249b2020-11-03 12:18:22 -05001893 if (!this->writeFunctionDeclaration(f.declaration())) {
1894 return;
1895 }
1896
John Stiles986c7fb2020-12-01 14:44:56 -05001897 fCurrentFunction = &f.declaration();
1898 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1899
John Stiles569249b2020-11-03 12:18:22 -05001900 this->writeLine(" {");
1901
John Stilese8da4d22021-03-24 09:19:45 -04001902 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001903 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001904 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001905 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001906 }
John Stilesc67b3622020-05-28 17:53:13 -04001907
John Stiles95680232021-04-22 15:05:20 -04001908 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001909 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001910 {
1911 AutoOutputStream outputToBuffer(this, &buffer);
1912 fIndentation++;
1913 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1914 if (!stmt->isEmpty()) {
1915 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001916 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001917 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001918 }
John Stilese8da4d22021-03-24 09:19:45 -04001919 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001920 // If the main function doesn't end with a return, we need to synthesize one here.
1921 if (!is_block_ending_with_return(f.body().get())) {
1922 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001923 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001924 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001925 }
John Stiles44532372020-12-07 12:33:55 -05001926 fIndentation--;
1927 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001928 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001929 this->write(fFunctionHeader);
1930 this->write(buffer.str());
1931}
1932
Brian Osman58134e12021-05-13 14:51:07 -04001933void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001934 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1935 this->write("thread ");
1936 }
1937 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001938 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001939 }
1940}
1941
1942void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001943 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001944 return;
1945 }
Brian Osman58134e12021-05-13 14:51:07 -04001946 this->writeModifiers(intf.variable().modifiers());
Timothy Liangdc89f192018-06-13 09:20:31 -04001947 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001948 this->writeLine(intf.typeName() + " {");
1949 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001950 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001951 structType = &structType->componentType();
1952 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001953 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001954 this->writeFields(structType->fields(), structType->fOffset, &intf);
Brian Salomond8d85b92021-07-07 09:41:17 -04001955 if (fProgram.fInputs.fUseFlipRTUniform) {
1956 this->writeLine("float2 " SKSL_RTFLIP_NAME ";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001957 }
1958 fIndentation--;
1959 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001960 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001961 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001962 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001963 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001964 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001965 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001966 this->write("]");
1967 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001968 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001969 } else {
Ethan Nicholas3533ff12021-08-02 12:53:29 -04001970 fInterfaceBlockNameMap[&intf] = *fProgram.fSymbols->takeOwnershipOfString("_anonInterface" +
1971 to_string(fAnonInterfaceCount++));
Ethan Nicholascc305772017-10-13 16:17:45 -04001972 }
1973 this->writeLine(";");
1974}
1975
Timothy Liangdc89f192018-06-13 09:20:31 -04001976void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1977 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001978 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001979 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001980 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001981 int fieldOffset = field.fModifiers.fLayout.fOffset;
1982 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001983 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001984 fContext.fErrors->error(parentOffset, "type '" + fieldType->name() +
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001985 "' is not permitted here");
John Stiles0023c0c2020-11-16 13:32:18 -05001986 return;
1987 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001988 if (fieldOffset != -1) {
1989 if (currentOffset > fieldOffset) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04001990 fContext.fErrors->error(parentOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04001991 "offset of field '" + field.fName + "' must be at least " +
1992 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001993 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001994 } else if (currentOffset < fieldOffset) {
1995 this->write("char pad");
1996 this->write(to_string(fPaddingCount++));
1997 this->write("[");
1998 this->write(to_string(fieldOffset - currentOffset));
1999 this->writeLine("];");
2000 currentOffset = fieldOffset;
2001 }
2002 int alignment = memoryLayout.alignment(*fieldType);
2003 if (fieldOffset % alignment) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002004 fContext.fErrors->error(parentOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002005 "offset of field '" + field.fName + "' must be a multiple of " +
2006 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04002007 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04002008 }
2009 }
Brian Osman8609a242020-09-08 14:01:49 -04002010 size_t fieldSize = memoryLayout.size(*fieldType);
2011 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002012 fContext.fErrors->error(parentOffset, "field offset overflow");
Brian Osman8609a242020-09-08 14:01:49 -04002013 return;
2014 }
2015 currentOffset += fieldSize;
Brian Osman58134e12021-05-13 14:51:07 -04002016 this->writeModifiers(field.fModifiers);
John Stilesb4418502021-02-04 10:57:08 -05002017 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04002018 this->write(" ");
2019 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04002020 this->writeLine(";");
2021 if (parentIntf) {
2022 fInterfaceBlockMap[&field] = parentIntf;
2023 }
2024 }
2025}
2026
Ethan Nicholascc305772017-10-13 16:17:45 -04002027void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05002028 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002029}
2030
Ethan Nicholas962dec42021-06-10 13:06:39 -04002031void MetalCodeGenerator::writeName(skstd::string_view name) {
Timothy Liang651286f2018-06-07 09:55:33 -04002032 if (fReservedWords.find(name) != fReservedWords.end()) {
2033 this->write("_"); // adding underscore before name to avoid conflict with reserved words
2034 }
2035 this->write(name);
2036}
2037
Brian Osman58134e12021-05-13 14:51:07 -04002038void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl) {
2039 this->writeModifiers(varDecl.var().modifiers());
John Stilesb4418502021-02-04 10:57:08 -05002040 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04002041 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002042 this->writeName(varDecl.var().name());
2043 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04002044 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05002045 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04002046 }
2047 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04002048}
2049
2050void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002051 switch (s.kind()) {
2052 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04002053 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002054 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002055 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05002056 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002057 this->write(";");
2058 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002059 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04002060 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002061 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002062 case Statement::Kind::kVarDeclaration:
Brian Osman58134e12021-05-13 14:51:07 -04002063 this->writeVarDeclaration(s.as<VarDeclaration>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002064 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002065 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04002066 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002067 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002068 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04002069 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002070 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002071 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04002072 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002073 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002074 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04002075 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002076 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002077 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04002078 this->write("break;");
2079 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002080 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04002081 this->write("continue;");
2082 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002083 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04002084 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04002085 break;
John Stiles98c1f822020-09-09 14:18:53 -04002086 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04002087 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04002088 this->write(";");
2089 break;
2090 default:
John Stileseada7bc2021-02-02 16:29:32 -05002091 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002092 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002093 }
2094}
2095
Ethan Nicholascc305772017-10-13 16:17:45 -04002096void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05002097 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
2098 // something here to make the code valid).
2099 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002100 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002101 this->writeLine("{");
2102 fIndentation++;
2103 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002104 for (const std::unique_ptr<Statement>& stmt : b.children()) {
2105 if (!stmt->isEmpty()) {
2106 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05002107 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002108 }
2109 }
2110 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04002111 fIndentation--;
2112 this->write("}");
2113 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002114}
2115
2116void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
2117 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05002118 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002119 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002120 this->writeStatement(*stmt.ifTrue());
2121 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002122 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002123 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04002124 }
2125}
2126
2127void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05002128 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
2129 if (!f.initializer() && f.test() && !f.next()) {
2130 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05002131 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05002132 this->write(") ");
2133 this->writeStatement(*f.statement());
2134 return;
2135 }
2136
John Stiles1a15e572021-04-19 14:57:15 -04002137 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002138 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04002139 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04002140 } else {
John Stiles1a15e572021-04-19 14:57:15 -04002141 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04002142 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002143 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05002144 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002145 }
2146 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002147 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05002148 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002149 }
2150 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002151 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002152}
2153
Ethan Nicholascc305772017-10-13 16:17:45 -04002154void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
2155 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002156 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002157 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05002158 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002159 this->write(");");
2160}
2161
2162void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
2163 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05002164 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002165 this->writeLine(") {");
2166 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002167 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
2168 const SwitchCase& c = stmt->as<SwitchCase>();
2169 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002170 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05002171 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002172 this->writeLine(":");
2173 } else {
2174 this->writeLine("default:");
2175 }
John Stilesb23a64b2021-03-11 08:27:59 -05002176 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05002177 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002178 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05002179 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05002180 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04002181 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002182 }
2183 fIndentation--;
2184 this->write("}");
2185}
2186
John Stiles986c7fb2020-12-01 14:44:56 -05002187void MetalCodeGenerator::writeReturnStatementFromMain() {
2188 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05002189 switch (fProgram.fConfig->fKind) {
Brian Salomon3e2fe2b2021-06-02 09:16:30 -04002190 case ProgramKind::kVertex:
John Stilesdbd4e6f2021-02-16 13:29:15 -05002191 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05002192 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05002193 break;
John Stiles986c7fb2020-12-01 14:44:56 -05002194 default:
2195 SkDEBUGFAIL("unsupported kind of program");
2196 }
2197}
2198
Ethan Nicholascc305772017-10-13 16:17:45 -04002199void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002200 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002201 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002202 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2203 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002204 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002205 this->writeLine(";");
2206 } else {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002207 fContext.fErrors->error(r.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002208 "Metal does not support returning '" +
2209 r.expression()->type().description() + "' from main()");
John Stiles97d18172021-01-22 16:47:42 -05002210 }
John Stiles986c7fb2020-12-01 14:44:56 -05002211 }
2212 this->writeReturnStatementFromMain();
2213 return;
2214 }
2215
Ethan Nicholascc305772017-10-13 16:17:45 -04002216 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002217 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002218 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002219 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002220 }
2221 this->write(";");
2222}
2223
Michael Ludwigbf58add2021-03-16 10:40:11 -04002224void MetalCodeGenerator::writeHeader() {
2225 this->write("#include <metal_stdlib>\n");
2226 this->write("#include <simd/simd.h>\n");
2227 this->write("using namespace metal;\n");
2228}
2229
Ethan Nicholascc305772017-10-13 16:17:45 -04002230void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002231 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002232 if (e->is<GlobalVarDeclaration>()) {
2233 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002234 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002235 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002236 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002237 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002238 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002239 if (-1 == fUniformBuffer) {
2240 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002241 fUniformBuffer = uniformSet;
2242 } else if (uniformSet != fUniformBuffer) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002243 fContext.fErrors->error(decls.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002244 "Metal backend requires all uniforms to have the same "
2245 "'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002246 }
2247 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002248 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002249 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002250 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002251 this->write(";\n");
2252 }
2253 }
2254 }
2255 if (-1 != fUniformBuffer) {
2256 this->write("};\n");
2257 }
2258}
2259
2260void MetalCodeGenerator::writeInputStruct() {
2261 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002262 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002263 if (e->is<GlobalVarDeclaration>()) {
2264 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002265 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002266 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2267 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002268 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002269 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002270 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002271 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002272 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002273 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002274 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002275 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002276 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002277 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002278 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002279 }
2280 }
2281 this->write(";\n");
2282 }
2283 }
2284 }
2285 this->write("};\n");
2286}
2287
2288void MetalCodeGenerator::writeOutputStruct() {
2289 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002290 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002291 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002292 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002293 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002294 }
Brian Osman133724c2020-10-28 14:14:39 -04002295 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002296 if (e->is<GlobalVarDeclaration>()) {
2297 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002298 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002299 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2300 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002301 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002302 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002303 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002304 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002305
2306 int location = var.modifiers().fLayout.fLocation;
2307 if (location < 0) {
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002308 fContext.fErrors->error(var.fOffset,
Ethan Nicholas3abc6c62021-08-13 11:20:09 -04002309 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002310 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002311 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002312 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002313 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002314 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002315 if (colorIndex) {
2316 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002317 }
Brian Osmanc0213602020-10-06 14:43:32 -04002318 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002319 }
2320 this->write(";\n");
2321 }
2322 }
Timothy Liang7d637782018-06-05 09:58:07 -04002323 }
John Stiles270cec22021-02-17 12:59:36 -05002324 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002325 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002326 }
2327 this->write("};\n");
2328}
2329
2330void MetalCodeGenerator::writeInterfaceBlocks() {
2331 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002332 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002333 if (e->is<InterfaceBlock>()) {
2334 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002335 wroteInterfaceBlock = true;
2336 }
2337 }
Brian Salomond8d85b92021-07-07 09:41:17 -04002338 if (!wroteInterfaceBlock && fProgram.fInputs.fUseFlipRTUniform) {
Timothy Liang7d637782018-06-05 09:58:07 -04002339 this->writeLine("struct sksl_synthetic_uniforms {");
Brian Salomond8d85b92021-07-07 09:41:17 -04002340 this->writeLine(" float2 " SKSL_RTFLIP_NAME ";");
Timothy Liang7d637782018-06-05 09:58:07 -04002341 this->writeLine("};");
2342 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002343}
2344
John Stilesdc75a972020-11-25 16:24:55 -05002345void MetalCodeGenerator::writeStructDefinitions() {
2346 for (const ProgramElement* e : fProgram.elements()) {
2347 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002348 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002349 }
2350 }
2351}
2352
John Stilescdcdb042020-07-06 09:03:51 -04002353void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2354 // Visit the interface blocks.
2355 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002356 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002357 }
Brian Osman133724c2020-10-28 14:14:39 -04002358 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002359 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002360 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002361 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002362 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2363 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2364 const Variable& var = decl.var();
Brian Osman58134e12021-05-13 14:51:07 -04002365 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2366 // Samplers are represented as a "texture/sampler" duo in the global struct.
2367 visitor->visitTexture(var.type(), var.name());
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002368 visitor->visitSampler(var.type(), var.name() + SAMPLER_SUFFIX);
Brian Osman58134e12021-05-13 14:51:07 -04002369 continue;
2370 }
2371
2372 if (!(var.modifiers().fFlags & ~Modifiers::kConst_Flag) &&
2373 -1 == var.modifiers().fLayout.fBuiltin) {
2374 // Visit a regular variable.
2375 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002376 }
2377 }
John Stilescdcdb042020-07-06 09:03:51 -04002378}
2379
2380void MetalCodeGenerator::writeGlobalStruct() {
2381 class : public GlobalStructVisitor {
2382 public:
Ethan Nicholas962dec42021-06-10 13:06:39 -04002383 void visitInterfaceBlock(const InterfaceBlock& block,
2384 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002385 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002386 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002387 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002388 fCodeGen->write("* ");
2389 fCodeGen->writeName(blockName);
2390 fCodeGen->write(";\n");
2391 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002392 void visitTexture(const Type& type, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002393 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002394 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002395 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002396 fCodeGen->write(" ");
2397 fCodeGen->writeName(name);
2398 fCodeGen->write(";\n");
2399 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002400 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002401 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002402 fCodeGen->write(" sampler ");
2403 fCodeGen->writeName(name);
2404 fCodeGen->write(";\n");
2405 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002406 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002407 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002408 fCodeGen->write(" ");
Brian Osman58134e12021-05-13 14:51:07 -04002409 fCodeGen->writeModifiers(var.modifiers());
John Stilesb4418502021-02-04 10:57:08 -05002410 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002411 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002412 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002413 fCodeGen->write(";\n");
2414 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002415 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002416 if (fFirst) {
2417 fCodeGen->write("struct Globals {\n");
2418 fFirst = false;
2419 }
2420 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002421 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002422 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002423 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002424 fFirst = true;
2425 }
2426 }
2427
2428 MetalCodeGenerator* fCodeGen = nullptr;
2429 bool fFirst = true;
2430 } visitor;
2431
2432 visitor.fCodeGen = this;
2433 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002434 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002435}
2436
2437void MetalCodeGenerator::writeGlobalInit() {
2438 class : public GlobalStructVisitor {
2439 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002440 void visitInterfaceBlock(const InterfaceBlock& blockType,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002441 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002442 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002443 fCodeGen->write("&");
2444 fCodeGen->writeName(blockName);
2445 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002446 void visitTexture(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002447 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002448 fCodeGen->writeName(name);
2449 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002450 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002451 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002452 fCodeGen->writeName(name);
2453 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002454 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002455 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002456 if (value) {
2457 fCodeGen->writeVarInitializer(var, *value);
2458 } else {
2459 fCodeGen->write("{}");
2460 }
2461 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002462 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002463 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002464 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002465 fFirst = false;
2466 } else {
2467 fCodeGen->write(", ");
2468 }
2469 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002470 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002471 if (!fFirst) {
2472 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002473 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002474 }
2475 }
2476 MetalCodeGenerator* fCodeGen = nullptr;
2477 bool fFirst = true;
2478 } visitor;
2479
2480 visitor.fCodeGen = this;
2481 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002482 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002483}
2484
Ethan Nicholascc305772017-10-13 16:17:45 -04002485void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002486 switch (e.kind()) {
2487 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002488 break;
Brian Osman58134e12021-05-13 14:51:07 -04002489 case ProgramElement::Kind::kGlobalVar:
Ethan Nicholascc305772017-10-13 16:17:45 -04002490 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002491 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002492 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002493 break;
John Stilesdc75a972020-11-25 16:24:55 -05002494 case ProgramElement::Kind::kStructDefinition:
2495 // Handled in writeStructDefinitions. Do nothing.
2496 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002497 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002498 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002499 break;
John Stiles569249b2020-11-03 12:18:22 -05002500 case ProgramElement::Kind::kFunctionPrototype:
2501 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2502 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002503 case ProgramElement::Kind::kModifiers:
Brian Osman58134e12021-05-13 14:51:07 -04002504 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers());
Ethan Nicholascc305772017-10-13 16:17:45 -04002505 this->writeLine(";");
2506 break;
2507 default:
John Stileseada7bc2021-02-02 16:29:32 -05002508 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002509 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002510 }
2511}
2512
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002513MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2514 if (!e) {
2515 return kNo_Requirements;
2516 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002517 switch (e->kind()) {
2518 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002519 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002520 Requirements result = this->requirements(f.function());
2521 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002522 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002523 }
2524 return result;
2525 }
John Stiles8cad6372021-04-07 12:31:13 -04002526 case Expression::Kind::kConstructorCompound:
2527 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002528 case Expression::Kind::kConstructorArray:
John Stilese3ae9682021-08-05 10:35:01 -04002529 case Expression::Kind::kConstructorArrayCast:
John Stiles2938eea2021-04-01 18:58:25 -04002530 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002531 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002532 case Expression::Kind::kConstructorSplat:
2533 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002534 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002535 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002536 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002537 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002538 }
2539 return result;
2540 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002541 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002542 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002543 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002544 return kGlobals_Requirement;
2545 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002546 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002547 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002548 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002549 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002550 case Expression::Kind::kBinary: {
2551 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002552 return this->requirements(bin.left().get()) |
2553 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002554 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002555 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002556 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002557 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002558 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002559 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002560 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002561 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002562 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002563 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002564 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002565 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2566 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002567 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002568 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002569 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002570 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002571 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002572 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002573 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002574 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002575 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002576 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002577 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002578 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002579 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002580 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002581 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002582 } else {
2583 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002584 }
2585 }
2586 return result;
2587 }
2588 default:
2589 return kNo_Requirements;
2590 }
2591}
2592
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002593MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2594 if (!s) {
2595 return kNo_Requirements;
2596 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002597 switch (s->kind()) {
2598 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002599 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002600 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002601 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002602 }
2603 return result;
2604 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002605 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002606 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002607 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002608 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002609 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002610 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002611 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002612 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002613 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002614 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002615 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002616 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002617 return this->requirements(i.test().get()) |
2618 this->requirements(i.ifTrue().get()) |
2619 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002620 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002621 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002622 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002623 return this->requirements(f.initializer().get()) |
2624 this->requirements(f.test().get()) |
2625 this->requirements(f.next().get()) |
2626 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002627 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002628 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002629 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002630 return this->requirements(d.test().get()) |
2631 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002632 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002633 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002634 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002635 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002636 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2637 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002638 }
2639 return result;
2640 }
2641 default:
2642 return kNo_Requirements;
2643 }
2644}
2645
2646MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002647 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002648 return kNo_Requirements;
2649 }
2650 auto found = fRequirements.find(&f);
2651 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002652 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002653 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002654 if (e->is<FunctionDefinition>()) {
2655 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002656 if (&def.declaration() == &f) {
2657 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002658 fRequirements[&f] = reqs;
2659 return reqs;
2660 }
2661 }
2662 }
John Stiles569249b2020-11-03 12:18:22 -05002663 // We never found a definition for this declared function, but it's legal to prototype a
2664 // function without ever giving a definition, as long as you don't call it.
2665 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002666 }
2667 return found->second;
2668}
2669
Timothy Liangb8eeb802018-07-23 16:46:16 -04002670bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002671 StringStream header;
2672 {
2673 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002674 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002675 this->writeStructDefinitions();
2676 this->writeUniformStruct();
2677 this->writeInputStruct();
2678 this->writeOutputStruct();
2679 this->writeInterfaceBlocks();
2680 this->writeGlobalStruct();
2681 }
2682 StringStream body;
2683 {
2684 AutoOutputStream outputToBody(this, &body, &fIndentation);
2685 for (const ProgramElement* e : fProgram.elements()) {
2686 this->writeProgramElement(*e);
2687 }
2688 }
2689 write_stringstream(header, *fOut);
John Stiles82d4c122021-08-10 16:03:23 -04002690 write_stringstream(fExtraFunctionPrototypes, *fOut);
John Stiles44532372020-12-07 12:33:55 -05002691 write_stringstream(fExtraFunctions, *fOut);
2692 write_stringstream(body, *fOut);
Ethan Nicholas0f36d112021-08-23 15:27:36 -04002693 fContext.fErrors->reportPendingErrors(PositionInfo());
Ethan Nicholas39f6da42021-08-23 13:10:07 -04002694 return fContext.fErrors->errorCount() == 0;
Ethan Nicholascc305772017-10-13 16:17:45 -04002695}
2696
John Stilesa6841be2020-08-06 14:11:56 -04002697} // namespace SkSL