blob: c8bc3b28200b93d9822cfce610bc898fa214dced [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 Stiles8cad6372021-04-07 12:31:13 -040014#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stiles7384b372021-04-01 13:48:15 -040015#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040016#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040017#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040018#include "src/sksl/ir/SkSLConstructorStruct.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLExpressionStatement.h"
20#include "src/sksl/ir/SkSLExtension.h"
21#include "src/sksl/ir/SkSLIndexExpression.h"
22#include "src/sksl/ir/SkSLModifiersDeclaration.h"
23#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050024#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040026
Brian Osmanc262a122020-08-06 16:34:34 -040027#include <algorithm>
28
Ethan Nicholascc305772017-10-13 16:17:45 -040029namespace SkSL {
30
John Stiles45990502021-02-16 10:55:27 -050031const char* MetalCodeGenerator::OperatorName(Operator op) {
32 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050033 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050034 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050035 }
36}
37
John Stilescdcdb042020-07-06 09:03:51 -040038class MetalCodeGenerator::GlobalStructVisitor {
39public:
40 virtual ~GlobalStructVisitor() = default;
Ethan Nicholasd2e09602021-06-10 11:21:59 -040041 virtual void visitInterfaceBlock(const InterfaceBlock& block, StringFragment blockName) = 0;
42 virtual void visitTexture(const Type& type, StringFragment name) = 0;
43 virtual void visitSampler(const Type& type, StringFragment name) = 0;
John Stilesfdb8dbe2020-12-04 11:00:03 -050044 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040045};
46
Ethan Nicholasd2e09602021-06-10 11:21:59 -040047void MetalCodeGenerator::write(StringFragment s) {
48 if (s.empty()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040049 return;
50 }
51 if (fAtLineStart) {
52 for (int i = 0; i < fIndentation; i++) {
53 fOut->writeText(" ");
54 }
55 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -040056 fOut->writeText(String(s).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -040057 fAtLineStart = false;
58}
59
Ethan Nicholasd2e09602021-06-10 11:21:59 -040060void MetalCodeGenerator::writeLine(StringFragment s) {
Ethan Nicholascc305772017-10-13 16:17:45 -040061 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050062 fOut->writeText(fLineEnding);
63 fAtLineStart = true;
64}
65
66void MetalCodeGenerator::finishLine() {
67 if (!fAtLineStart) {
68 this->writeLine();
69 }
Ethan Nicholascc305772017-10-13 16:17:45 -040070}
71
72void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040073 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040074}
75
Ethan Nicholas45fa8102020-01-13 10:58:49 -050076String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040077 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -050078 case Type::TypeKind::kArray:
79 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
80 return String::printf("array<%s, %d>",
81 this->typeName(type.componentType()).c_str(), type.columns());
82
Ethan Nicholase6592142020-09-08 10:22:09 -040083 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -050085
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050087 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
88 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -050089
Ethan Nicholase6592142020-09-08 10:22:09 -040090 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -050091 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -050092
John Stilesfd41d872020-11-25 22:39:45 -050093 case Type::TypeKind::kEnum:
94 return "int";
John Stilesb4418502021-02-04 10:57:08 -050095
Ethan Nicholascc305772017-10-13 16:17:45 -040096 default:
John Stiles54e7c052021-01-11 14:22:36 -050097 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -040098 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholasd2e09602021-06-10 11:21:59 -040099 return String(fContext.fTypes.fFloat->name());
Timothy Liang7d637782018-06-05 09:58:07 -0400100 } else {
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400101 return String(type.name());
Timothy Liang7d637782018-06-05 09:58:07 -0400102 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400103 }
104}
105
Brian Osman02bc5222021-01-28 11:00:20 -0500106void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
107 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500108 this->writeLine("struct " + type.name() + " {");
109 fIndentation++;
110 this->writeFields(type.fields(), type.fOffset);
111 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500112 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500113}
114
John Stilesb4418502021-02-04 10:57:08 -0500115void MetalCodeGenerator::writeType(const Type& type) {
116 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500117}
118
Ethan Nicholascc305772017-10-13 16:17:45 -0400119void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400120 switch (expr.kind()) {
121 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400122 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400123 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400124 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400125 this->writeBoolLiteral(expr.as<BoolLiteral>());
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 Stiles8cad6372021-04-07 12:31:13 -0400131 case Expression::Kind::kConstructorCompound:
132 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400133 break;
134 case Expression::Kind::kConstructorDiagonalMatrix:
135 case Expression::Kind::kConstructorSplat:
136 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400137 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400138 case Expression::Kind::kConstructorMatrixResize:
139 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
140 parentPrecedence);
141 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400142 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400143 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400144 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400145 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400146 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400147 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -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;
Ethan Nicholase6592142020-09-08 10:22:09 -0400152 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400153 this->writeFloatLiteral(expr.as<FloatLiteral>());
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
Brian Osman93aed9a2020-12-28 15:18:46 -0500464static constexpr char kMatrixCompMult[] = R"(
465template <int C, int R>
466matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
467 matrix<float, C, R> result;
468 for (int c = 0; c < C; ++c) {
469 result[c] = a[c] * b[c];
470 }
471 return result;
472}
473)";
474
475void MetalCodeGenerator::writeMatrixCompMult() {
476 String name = "matrixCompMult";
477 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
478 fWrittenIntrinsics.insert(name);
479 fExtraFunctions.writeText(kMatrixCompMult);
480 }
481}
482
John Stiles86424eb2020-12-11 11:17:14 -0500483String MetalCodeGenerator::getTempVariable(const Type& type) {
484 String tempVar = "_skTemp" + to_string(fVarCount++);
485 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
486 return tempVar;
487}
488
John Stiles791c27d2020-12-30 14:56:57 -0500489void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
490 // Write out an intrinsic function call exactly as-is. No muss no fuss.
491 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500492 this->writeArgumentList(c.arguments());
493}
494
495void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500496 this->write("(");
497 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500498 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500499 this->write(separator);
500 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500501 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500502 }
503 this->write(")");
504}
505
John Stiles496b7d12021-05-06 10:26:45 -0400506bool MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400507 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400508 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400509 case k_sample_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500510 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400511 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500512 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400513 this->write(SAMPLER_SUFFIX);
514 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400515 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400516 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500517 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500518 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500519 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500520 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500521 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400522 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400523 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500524 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400525 this->write(")");
526 }
John Stiles496b7d12021-05-06 10:26:45 -0400527 return true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400528 }
John Stiles496b7d12021-05-06 10:26:45 -0400529 case k_mod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400530 // 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 -0500531 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500532 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500533 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500534 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500535 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500536 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500537 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
John Stiles496b7d12021-05-06 10:26:45 -0400538 return true;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500539 }
Brian Osman46787d52020-11-24 14:18:23 -0500540 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stiles496b7d12021-05-06 10:26:45 -0400541 case k_distance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500542 if (arguments[0]->type().columns() == 1) {
543 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500544 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500545 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500546 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500547 this->write(")");
548 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500549 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500550 }
John Stiles496b7d12021-05-06 10:26:45 -0400551 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500552 }
John Stiles496b7d12021-05-06 10:26:45 -0400553 case k_dot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500554 if (arguments[0]->type().columns() == 1) {
555 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500556 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500557 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500558 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500559 this->write(")");
560 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500561 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500562 }
John Stiles496b7d12021-05-06 10:26:45 -0400563 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500564 }
John Stiles496b7d12021-05-06 10:26:45 -0400565 case k_faceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500566 if (arguments[0]->type().columns() == 1) {
567 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
568 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500569 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500570 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500571 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500572 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500573 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500574 this->write("))");
575 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500576 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500577 }
John Stiles496b7d12021-05-06 10:26:45 -0400578 return true;
John Stilesad0571f2020-12-10 18:03:10 -0500579 }
John Stiles496b7d12021-05-06 10:26:45 -0400580 case k_length_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500581 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500582 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500583 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400584 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500585 }
John Stiles496b7d12021-05-06 10:26:45 -0400586 case k_normalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500587 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500588 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500589 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400590 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500591 }
John Stiles496b7d12021-05-06 10:26:45 -0400592
593 case k_floatBitsToInt_IntrinsicKind:
594 case k_floatBitsToUint_IntrinsicKind:
595 case k_intBitsToFloat_IntrinsicKind:
596 case k_uintBitsToFloat_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500597 this->write(this->getBitcastIntrinsic(c.type()));
598 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500599 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500600 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400601 return true;
John Stiles0063a9f2020-12-10 18:01:45 -0500602 }
John Stiles496b7d12021-05-06 10:26:45 -0400603 case k_degrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500604 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500605 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500606 this->write(") * 57.2957795)");
John Stiles496b7d12021-05-06 10:26:45 -0400607 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500608 }
John Stiles496b7d12021-05-06 10:26:45 -0400609 case k_radians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500610 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500611 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500612 this->write(") * 0.0174532925)");
John Stiles496b7d12021-05-06 10:26:45 -0400613 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500614 }
John Stiles496b7d12021-05-06 10:26:45 -0400615 case k_dFdx_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500616 this->write("dfdx");
617 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400618 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500619 }
John Stiles496b7d12021-05-06 10:26:45 -0400620 case k_dFdy_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500621 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500622 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500623 this->write("-");
624 }
625 this->write("dfdy");
626 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400627 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500628 }
John Stiles496b7d12021-05-06 10:26:45 -0400629 case k_inverse_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500630 this->write(this->getInversePolyfill(arguments));
631 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400632 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500633 }
John Stiles496b7d12021-05-06 10:26:45 -0400634 case k_inversesqrt_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500635 this->write("rsqrt");
636 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400637 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500638 }
John Stiles496b7d12021-05-06 10:26:45 -0400639 case k_atan_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500640 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
641 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400642 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500643 }
John Stiles496b7d12021-05-06 10:26:45 -0400644 case k_reflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500645 if (arguments[0]->type().columns() == 1) {
646 // We need to synthesize `I - 2 * N * I * N`.
647 String tmpI = this->getTempVariable(arguments[0]->type());
648 String tmpN = this->getTempVariable(arguments[1]->type());
649
650 // (_skTempI = ...
651 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500652 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500653
654 // , _skTempN = ...
655 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500656 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500657
658 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
659 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
660 } else {
661 this->writeSimpleIntrinsic(c);
662 }
John Stiles496b7d12021-05-06 10:26:45 -0400663 return true;
John Stiles791c27d2020-12-30 14:56:57 -0500664 }
John Stiles496b7d12021-05-06 10:26:45 -0400665 case k_refract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500666 if (arguments[0]->type().columns() == 1) {
667 // Metal does implement refract for vectors; rather than reimplementing refract from
668 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
669 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500670 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500671 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500672 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500673 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500674 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500675 this->write(").x)");
676 } else {
677 this->writeSimpleIntrinsic(c);
678 }
John Stiles496b7d12021-05-06 10:26:45 -0400679 return true;
John Stiles4b783d62020-12-30 14:58:07 -0500680 }
John Stiles496b7d12021-05-06 10:26:45 -0400681 case k_roundEven_IntrinsicKind: {
John Stiles23456532020-12-30 18:12:48 -0500682 this->write("rint");
683 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400684 return true;
John Stiles23456532020-12-30 18:12:48 -0500685 }
John Stiles496b7d12021-05-06 10:26:45 -0400686 case k_bitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500687 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500688 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500689 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400690 return true;
John Stilese7dc7cb2020-12-22 15:37:14 -0500691 }
John Stiles496b7d12021-05-06 10:26:45 -0400692 case k_findLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500693 // Create a temp variable to store the expression, to avoid double-evaluating it.
694 String skTemp = this->getTempVariable(arguments[0]->type());
695 String exprType = this->typeName(arguments[0]->type());
696
697 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
698 // Use select to detect zero inputs and force a -1 result.
699
700 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
701 this->write("(");
702 this->write(skTemp);
703 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500704 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500705 this->write("), select(ctz(");
706 this->write(skTemp);
707 this->write("), ");
708 this->write(exprType);
709 this->write("(-1), ");
710 this->write(skTemp);
711 this->write(" == ");
712 this->write(exprType);
713 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400714 return true;
John Stiles86424eb2020-12-11 11:17:14 -0500715 }
John Stiles496b7d12021-05-06 10:26:45 -0400716 case k_findMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500717 // Create a temp variable to store the expression, to avoid double-evaluating it.
718 String skTemp1 = this->getTempVariable(arguments[0]->type());
719 String exprType = this->typeName(arguments[0]->type());
720
721 // GLSL findMSB is actually quite different from Metal's clz:
722 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
723 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
724
725 // (_skTemp1 = (.....),
726 this->write("(");
727 this->write(skTemp1);
728 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500729 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500730 this->write("), ");
731
732 // Signed input types might be negative; we need another helper variable to negate the
733 // input (since we can only find one bits, not zero bits).
734 String skTemp2;
735 if (arguments[0]->type().isSigned()) {
736 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
737 skTemp2 = this->getTempVariable(arguments[0]->type());
738 this->write(skTemp2);
739 this->write(" = (select(");
740 this->write(skTemp1);
741 this->write(", ~");
742 this->write(skTemp1);
743 this->write(", ");
744 this->write(skTemp1);
745 this->write(" < 0)), ");
746 } else {
747 skTemp2 = skTemp1;
748 }
749
750 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
751 this->write("select(");
752 this->write(this->typeName(c.type()));
753 this->write("(clz(");
754 this->write(skTemp2);
755 this->write(")), ");
756 this->write(this->typeName(c.type()));
757 this->write("(-1), ");
758 this->write(skTemp2);
759 this->write(" == ");
760 this->write(exprType);
761 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400762 return true;
John Stiles9685e522020-12-14 11:52:14 -0500763 }
John Stiles496b7d12021-05-06 10:26:45 -0400764 case k_matrixCompMult_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500765 this->writeMatrixCompMult();
766 this->writeSimpleIntrinsic(c);
John Stiles496b7d12021-05-06 10:26:45 -0400767 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500768 }
John Stiles496b7d12021-05-06 10:26:45 -0400769 case k_equal_IntrinsicKind:
770 case k_greaterThan_IntrinsicKind:
771 case k_greaterThanEqual_IntrinsicKind:
772 case k_lessThan_IntrinsicKind:
773 case k_lessThanEqual_IntrinsicKind:
774 case k_notEqual_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500775 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500776 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500777 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400778 case k_equal_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500779 this->write(" == ");
780 break;
John Stiles496b7d12021-05-06 10:26:45 -0400781 case k_notEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500782 this->write(" != ");
783 break;
John Stiles496b7d12021-05-06 10:26:45 -0400784 case k_lessThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500785 this->write(" < ");
786 break;
John Stiles496b7d12021-05-06 10:26:45 -0400787 case k_lessThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500788 this->write(" <= ");
789 break;
John Stiles496b7d12021-05-06 10:26:45 -0400790 case k_greaterThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500791 this->write(" > ");
792 break;
John Stiles496b7d12021-05-06 10:26:45 -0400793 case k_greaterThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500794 this->write(" >= ");
795 break;
796 default:
John Stilesf57207b2021-02-02 17:50:34 -0500797 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500798 }
Brian Osman00185012021-02-04 16:07:11 -0500799 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500800 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400801 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500802 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400803 default:
John Stiles496b7d12021-05-06 10:26:45 -0400804 return false;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400805 }
806}
807
John Stilesfcf8cb22020-08-06 14:29:22 -0400808// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
809// Cells that don't exist in the source matrix will be populated with identity-matrix values.
810void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
811 SkASSERT(rows <= 4);
812 SkASSERT(columns <= 4);
813
814 const char* columnSeparator = "";
815 for (int c = 0; c < columns; ++c) {
816 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
817 columnSeparator = "), ";
818
819 // Determine how many values to take from the source matrix for this row.
820 int swizzleLength = 0;
821 if (c < sourceMatrix.columns()) {
822 swizzleLength = std::min<>(rows, sourceMatrix.rows());
823 }
824
825 // Emit all the values from the source matrix row.
826 bool firstItem;
827 switch (swizzleLength) {
828 case 0: firstItem = true; break;
829 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
830 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
831 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
832 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
833 default: SkUNREACHABLE;
834 }
835
836 // Emit the placeholder identity-matrix cells.
837 for (int r = swizzleLength; r < rows; ++r) {
838 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
839 firstItem = false;
840 }
841 }
842
843 fExtraFunctions.writeText(")");
844}
845
846// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
847// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400848void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles8e3b6be2020-10-13 11:14:08 -0400849 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400850 size_t argIndex = 0;
851 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400852 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400853
854 const char* columnSeparator = "";
855 for (int c = 0; c < columns; ++c) {
856 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
857 columnSeparator = "), ";
858
859 const char* rowSeparator = "";
860 for (int r = 0; r < rows; ++r) {
861 fExtraFunctions.writeText(rowSeparator);
862 rowSeparator = ", ";
863
864 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400865 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400866 switch (argType.typeKind()) {
867 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400868 fExtraFunctions.printf("x%zu", argIndex);
869 break;
870 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400871 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400872 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
873 break;
874 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400875 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400876 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
877 argPosition / argType.rows(),
878 argPosition % argType.rows());
879 break;
880 }
881 default: {
882 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
883 fExtraFunctions.writeText("<error>");
884 break;
885 }
886 }
887
888 ++argPosition;
889 if (argPosition >= argType.columns() * argType.rows()) {
890 ++argIndex;
891 argPosition = 0;
892 }
893 } else {
894 SkDEBUGFAIL("not enough arguments for matrix constructor");
895 fExtraFunctions.writeText("<error>");
896 }
897 }
898 }
899
900 if (argPosition != 0 || argIndex != args.size()) {
901 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
902 fExtraFunctions.writeText(", <error>");
903 }
904
905 fExtraFunctions.writeText(")");
906}
907
John Stiles1bdafbf2020-05-28 12:17:20 -0400908// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
909// Keeps track of previously generated constructors so that we won't generate more than one
910// constructor for any given permutation of input argument types. Returns the name of the
911// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400912String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400913 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500914 int columns = matrix.columns();
915 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400916 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400917
918 // Create the helper-method name and use it as our lookup key.
919 String name;
920 name.appendf("float%dx%d_from", columns, rows);
921 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500922 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400923 }
924
925 // If a helper-method has already been synthesized, we don't need to synthesize it again.
926 auto [iter, newlyCreated] = fHelpers.insert(name);
927 if (!newlyCreated) {
928 return name;
929 }
930
931 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
932 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
933 // supply a mixture of scalars and vectors.)
934 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
935
936 size_t argIndex = 0;
937 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400938 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400939 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500940 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400941 argSeparator = ", ";
942 }
943
944 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
945
John Stiles9aeed132020-11-24 17:36:06 -0500946 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400947 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400948 } else {
John Stiles5abb9e12021-04-06 13:47:19 -0400949 this->assembleMatrixFromExpressions(c, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400950 }
951
John Stilesfcf8cb22020-08-06 14:29:22 -0400952 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500953 return name;
954}
955
956bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
957 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
958 return false;
959 }
960 if (t1.columns() > 1) {
961 return this->canCoerce(t1.componentType(), t2.componentType());
962 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500963 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500964}
965
John Stiles8cad6372021-04-07 12:31:13 -0400966bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -0400967 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -0400968
969 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
970 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
971 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
972 // scalars can be constructed trivially. In more complex cases, we generate a helper function
973 // that converts our inputs into a properly-shaped matrix.
974 // A matrix construct helper method is always used if any input argument is a matrix.
975 // Helper methods are also necessary when any argument would span multiple rows. For instance:
976 //
977 // float2 x = (1, 2);
978 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
979 // | 2 4 6 |
980 //
981 // float2 x = (2, 3);
982 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
983 // | 2 4 6 |
984 //
985 // float4 x = (1, 2, 3, 4);
986 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
987 // | 2 4 |
988 //
989
990 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400991 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400992 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500993 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400994 return true;
995 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400996 position += expr->type().columns();
997 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400998 // An input argument would span multiple rows; a helper function is required.
999 return true;
1000 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001001 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001002 // We've advanced to the end of a row. Wrap to the start of the next row.
1003 position = 0;
1004 }
1005 }
1006
1007 return false;
1008}
1009
John Stiles5abb9e12021-04-06 13:47:19 -04001010void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1011 Precedence parentPrecedence) {
1012 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1013 // matrix-construct helper here.
1014 this->write(this->getMatrixConstructHelper(c));
1015 this->write("(");
1016 this->writeExpression(*c.argument(), Precedence::kSequence);
1017 this->write(")");
1018}
1019
John Stiles8cad6372021-04-07 12:31:13 -04001020void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1021 Precedence parentPrecedence) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001022 if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001023 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001024 } else {
1025 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1026 }
1027}
John Stiles7384b372021-04-01 13:48:15 -04001028
John Stiles8cad6372021-04-07 12:31:13 -04001029void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1030 Precedence parentPrecedence) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001031 // Emit and invoke a matrix-constructor helper method if one is necessary.
1032 if (this->matrixConstructHelperIsNeeded(c)) {
1033 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001034 this->write("(");
1035 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001036 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001037 this->write(separator);
1038 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001039 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001040 }
John Stiles1fa15b12020-05-28 17:36:54 +00001041 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001042 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001043 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001044
John Stiles2bec8ab2021-04-06 18:40:04 -04001045 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1046 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1047 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1048 // can group our inputs up and synthesize a constructor for each column.
1049 const Type& matrixType = c.type();
1050 const Type& columnType = matrixType.componentType().toCompound(
1051 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1052
1053 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001054 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001055 const char* separator = "";
1056 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001057 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001058 this->write(separator);
1059 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001060 if (arg->type().columns() < matrixType.rows()) {
1061 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001062 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001063 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001064 this->write("(");
1065 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001066 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001067 }
Brian Osman00185012021-02-04 16:07:11 -05001068 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001069 if (scalarCount && scalarCount == matrixType.rows()) {
1070 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001071 this->write(")");
1072 scalarCount = 0;
1073 }
1074 }
John Stiles7384b372021-04-01 13:48:15 -04001075 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001076}
1077
John Stilesb14a8192021-04-05 11:40:46 -04001078void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1079 const char* leftBracket,
1080 const char* rightBracket,
1081 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001082 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001083 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001084 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001085 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001086 this->write(separator);
1087 separator = ", ";
1088 this->writeExpression(*arg, Precedence::kSequence);
1089 }
John Stilesb14a8192021-04-05 11:40:46 -04001090 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001091}
1092
John Stilesb14a8192021-04-05 11:40:46 -04001093void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1094 const char* leftBracket,
1095 const char* rightBracket,
1096 Precedence parentPrecedence) {
1097 // If the type is coercible, emit it directly without the cast.
1098 auto args = c.argumentSpan();
1099 if (args.size() == 1) {
1100 if (this->canCoerce(c.type(), args.front()->type())) {
1101 this->writeExpression(*args.front(), parentPrecedence);
1102 return;
1103 }
John Stilesfd7252f2021-04-04 22:24:40 -04001104 }
1105
John Stilesb14a8192021-04-05 11:40:46 -04001106 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001107}
1108
Ethan Nicholascc305772017-10-13 16:17:45 -04001109void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001110 if (fRTHeightName.length()) {
1111 this->write("float4(_fragCoord.x, ");
1112 this->write(fRTHeightName.c_str());
1113 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001114 } else {
1115 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1116 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001117}
1118
1119void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001120 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001121 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001122 // we're actually targeting the clones.
1123 if (fIgnoreVariableReferenceModifiers) {
1124 this->writeName(ref.variable()->name());
1125 return;
1126 }
1127
Ethan Nicholas78686922020-10-08 06:46:27 -04001128 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001129 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001130 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001131 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001132 case SK_FRAGCOORD_BUILTIN:
1133 this->writeFragCoord();
1134 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001135 case SK_VERTEXID_BUILTIN:
1136 this->write("sk_VertexID");
1137 break;
1138 case SK_INSTANCEID_BUILTIN:
1139 this->write("sk_InstanceID");
1140 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001141 case SK_CLOCKWISE_BUILTIN:
1142 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001143 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001144 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001145 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001146 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001147 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001148 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001149 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001150 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001151 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001152 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001153 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1154 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001155 this->write("_uniforms.");
1156 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001157 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 }
1159 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001160 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001161 }
1162}
1163
1164void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001165 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001166 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001167 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001168 this->write("]");
1169}
1170
1171void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001172 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1173 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001174 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001175 this->write(".");
1176 }
Timothy Liang7d637782018-06-05 09:58:07 -04001177 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001178 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001179 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001180 break;
1181 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001182 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001183 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001184 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001185 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001186 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001187 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1188 this->write("->");
1189 }
Timothy Liang651286f2018-06-07 09:55:33 -04001190 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001191 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001192 }
1193}
1194
1195void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001196 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001197 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001198 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001199 SkASSERT(c >= 0 && c <= 3);
1200 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001201 }
1202}
1203
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001204void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1205 const Type& result) {
John Stilesc985e142021-05-13 14:01:48 -04001206 SkASSERT(left.isMatrix());
1207 SkASSERT(right.isMatrix());
1208 SkASSERT(result.isMatrix());
1209 SkASSERT(left.rows() == right.rows());
1210 SkASSERT(left.columns() == right.columns());
1211 SkASSERT(left.rows() == result.rows());
1212 SkASSERT(left.columns() == result.columns());
1213
1214 String key = "Matrix *= " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001215
1216 auto [iter, wasInserted] = fHelpers.insert(key);
1217 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001218 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001219 " left = left * right;\n"
1220 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001221 "}\n",
1222 this->typeName(result).c_str(), this->typeName(left).c_str(),
1223 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001224 }
1225}
1226
John Stiles39346472021-04-29 14:39:35 -04001227void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1228 SkASSERT(left.isMatrix());
1229 SkASSERT(right.isMatrix());
1230 SkASSERT(left.rows() == right.rows());
1231 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001232
John Stilesc985e142021-05-13 14:01:48 -04001233 String key = "Matrix == " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001234
1235 auto [iter, wasInserted] = fHelpers.insert(key);
1236 if (wasInserted) {
1237 fExtraFunctions.printf(
1238 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001239 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001240 this->typeName(left).c_str(), this->typeName(right).c_str());
1241
John Stiles39346472021-04-29 14:39:35 -04001242 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001243 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001244 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1245 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001246 }
John Stiles39346472021-04-29 14:39:35 -04001247
1248 fExtraFunctions.printf(
1249 ";\n"
1250 "}\n"
1251 "thread bool operator!=(const %s left, const %s right) {\n"
1252 " return !(left == right);\n"
1253 "}\n",
1254 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001255 }
1256}
1257
John Stilesc985e142021-05-13 14:01:48 -04001258void MetalCodeGenerator::writeMatrixDivisionHelpers(const Type& type) {
1259 SkASSERT(type.isMatrix());
1260
1261 String key = "Matrix / " + this->typeName(type);
1262
1263 auto [iter, wasInserted] = fHelpers.insert(key);
1264 if (wasInserted) {
1265 String typeName = this->typeName(type);
1266
1267 fExtraFunctions.printf(
1268 "thread %s operator/(const %s left, const %s right) {\n"
1269 " return %s(",
1270 typeName.c_str(), typeName.c_str(), typeName.c_str(), typeName.c_str());
1271
1272 const char* separator = "";
1273 for (int index=0; index<type.columns(); ++index) {
1274 fExtraFunctions.printf("%sleft[%d] / right[%d]", separator, index, index);
1275 separator = ", ";
1276 }
1277
1278 fExtraFunctions.printf(");\n"
1279 "}\n"
1280 "thread %s& operator/=(thread %s& left, thread const %s& right) {\n"
1281 " left = left / right;\n"
1282 " return left;\n"
1283 "}\n",
1284 typeName.c_str(), typeName.c_str(), typeName.c_str());
1285 }
1286}
1287
John Stiles39346472021-04-29 14:39:35 -04001288void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1289 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001290
John Stiles39346472021-04-29 14:39:35 -04001291 // If the array's component type needs a helper as well, we need to emit that one first.
1292 this->writeEqualityHelpers(type.componentType(), type.componentType());
1293
1294 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1295 if (wasInserted) {
1296 fExtraFunctions.writeText(R"(
1297template <typename T, size_t N>
1298bool operator==(thread const array<T, N>& left, thread const array<T, N>& right) {
1299 for (size_t index = 0; index < N; ++index) {
1300 if (!(left[index] == right[index])) {
1301 return false;
1302 }
1303 }
1304 return true;
1305}
1306
1307template <typename T, size_t N>
1308bool operator!=(thread const array<T, N>& left, thread const array<T, N>& right) {
1309 return !(left == right);
1310}
1311)");
1312 }
1313}
1314
1315void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1316 SkASSERT(type.isStruct());
1317 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001318
1319 auto [iter, wasInserted] = fHelpers.insert(key);
1320 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001321 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1322 for (const Type::Field& field : type.fields()) {
1323 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001324 }
John Stiles39346472021-04-29 14:39:35 -04001325
1326 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1327 // and GLSL but do not exist by default in Metal.
1328 fExtraFunctions.printf(
1329 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1330 " return ",
1331 this->typeName(type).c_str(),
1332 this->typeName(type).c_str());
1333
1334 const char* separator = "";
1335 for (const Type::Field& field : type.fields()) {
1336 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1337 separator,
1338 (int)field.fName.size(), field.fName.data(),
1339 (int)field.fName.size(), field.fName.data());
1340 separator = " &&\n ";
1341 }
1342 fExtraFunctions.printf(
1343 ";\n"
1344 "}\n"
1345 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1346 " return !(left == right);\n"
1347 "}\n",
1348 this->typeName(type).c_str(),
1349 this->typeName(type).c_str());
1350 }
1351}
1352
1353void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1354 if (leftType.isArray() && rightType.isArray()) {
1355 this->writeArrayEqualityHelpers(leftType);
1356 return;
1357 }
1358 if (leftType.isStruct() && rightType.isStruct()) {
1359 this->writeStructEqualityHelpers(leftType);
1360 return;
1361 }
1362 if (leftType.isMatrix() && rightType.isMatrix()) {
1363 this->writeMatrixEqualityHelpers(leftType, rightType);
1364 return;
John Stiles01cdf012021-02-10 09:53:41 -05001365 }
1366}
1367
John Stiles6b131292021-05-12 17:12:21 -04001368void MetalCodeGenerator::writeNumberAsMatrix(const Expression& expr, const Type& matrixType) {
1369 SkASSERT(expr.type().isNumber());
1370 SkASSERT(matrixType.isMatrix());
1371
1372 // Componentwise multiply the scalar against a matrix of the desired size which contains all 1s.
1373 this->write("(");
1374 this->writeType(matrixType);
1375 this->write("(");
1376
1377 const char* separator = "";
1378 for (int index = matrixType.slotCount(); index--;) {
1379 this->write(separator);
1380 this->write("1.0");
1381 separator = ", ";
1382 }
1383
1384 this->write(") * ");
1385 this->writeExpression(expr, Precedence::kMultiplicative);
1386 this->write(")");
1387}
1388
Ethan Nicholascc305772017-10-13 16:17:45 -04001389void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1390 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001391 const Expression& left = *b.left();
1392 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001393 const Type& leftType = left.type();
1394 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001395 Operator op = b.getOperator();
1396 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001397 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001398 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001399 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001400 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001401 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001402 this->write("all");
1403 needParens = true;
1404 }
1405 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001406 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001407 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001408 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001409 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001410 needParens = true;
1411 }
1412 break;
1413 default:
1414 break;
1415 }
John Stiles39346472021-04-29 14:39:35 -04001416 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1417 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001418 }
John Stilesc985e142021-05-13 14:01:48 -04001419 if (op.removeAssignment().kind() == Token::Kind::TK_SLASH &&
1420 ((leftType.isMatrix() && rightType.isMatrix()) ||
1421 (leftType.isScalar() && rightType.isMatrix()) ||
1422 (leftType.isMatrix() && rightType.isScalar()))) {
1423 this->writeMatrixDivisionHelpers(leftType.isMatrix() ? leftType : rightType);
1424 }
1425 if (needParens) {
1426 this->write("(");
1427 }
John Stiles6011bbc2021-05-19 22:56:18 -04001428 bool needMatrixSplatOnScalar = rightType.isMatrix() && leftType.isNumber() &&
1429 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001430 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1431 if (needMatrixSplatOnScalar) {
1432 this->writeNumberAsMatrix(left, rightType);
1433 } else {
1434 this->writeExpression(left, precedence);
1435 }
John Stiles45990502021-02-16 10:55:27 -05001436 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001437 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001438 // This doesn't compile in Metal:
1439 // float4 x = float4(1);
1440 // x.xy *= float2x2(...);
1441 // with the error message "non-const reference cannot bind to vector element",
1442 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1443 // as long as the LHS has no side effects, and hope for the best otherwise.
1444 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001445 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001446 this->write(" ");
John Stiles7cbe66b2021-05-12 17:01:23 -04001447 this->write(OperatorName(op.removeAssignment()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001448 this->write(" ");
1449 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001450 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001451 }
John Stiles6b131292021-05-12 17:12:21 -04001452
John Stiles6011bbc2021-05-19 22:56:18 -04001453 needMatrixSplatOnScalar = leftType.isMatrix() && rightType.isNumber() &&
1454 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001455 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1456 if (needMatrixSplatOnScalar) {
1457 this->writeNumberAsMatrix(right, leftType);
1458 } else {
1459 this->writeExpression(right, precedence);
1460 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001461 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001462 this->write(")");
1463 }
1464}
1465
1466void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1467 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001468 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001469 this->write("(");
1470 }
Brian Osman00185012021-02-04 16:07:11 -05001471 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001472 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001473 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001474 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001475 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1476 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001477 this->write(")");
1478 }
1479}
1480
1481void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1482 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001483 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001484 this->write("(");
1485 }
John Stilesd6449e92020-11-30 09:13:23 -05001486 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001487 this->writeExpression(*p.operand(), Precedence::kPrefix);
1488 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001489 this->write(")");
1490 }
1491}
1492
1493void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1494 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001495 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001496 this->write("(");
1497 }
Brian Osman00185012021-02-04 16:07:11 -05001498 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001499 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001500 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001501 this->write(")");
1502 }
1503}
1504
1505void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001506 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001507}
1508
1509void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001510 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001511 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001512 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001513 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001514 this->write(to_string(i.value() & 0xffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001515 } else {
John Stiles12739df2020-12-29 09:47:20 -05001516 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001517 }
1518}
1519
1520void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001521 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001522}
1523
1524void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001525 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001526}
1527
John Stiles06b84ef2020-12-09 12:35:48 -05001528void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1529 const char*& separator) {
1530 Requirements requirements = this->requirements(f);
1531 if (requirements & kInputs_Requirement) {
1532 this->write(separator);
1533 this->write("_in");
1534 separator = ", ";
1535 }
1536 if (requirements & kOutputs_Requirement) {
1537 this->write(separator);
1538 this->write("_out");
1539 separator = ", ";
1540 }
1541 if (requirements & kUniforms_Requirement) {
1542 this->write(separator);
1543 this->write("_uniforms");
1544 separator = ", ";
1545 }
1546 if (requirements & kGlobals_Requirement) {
1547 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001548 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001549 separator = ", ";
1550 }
1551 if (requirements & kFragCoord_Requirement) {
1552 this->write(separator);
1553 this->write("_fragCoord");
1554 separator = ", ";
1555 }
1556}
1557
1558void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1559 const char*& separator) {
1560 Requirements requirements = this->requirements(f);
1561 if (requirements & kInputs_Requirement) {
1562 this->write(separator);
1563 this->write("Inputs _in");
1564 separator = ", ";
1565 }
1566 if (requirements & kOutputs_Requirement) {
1567 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001568 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001569 separator = ", ";
1570 }
1571 if (requirements & kUniforms_Requirement) {
1572 this->write(separator);
1573 this->write("Uniforms _uniforms");
1574 separator = ", ";
1575 }
1576 if (requirements & kGlobals_Requirement) {
1577 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001578 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001579 separator = ", ";
1580 }
1581 if (requirements & kFragCoord_Requirement) {
1582 this->write(separator);
1583 this->write("float4 _fragCoord");
1584 separator = ", ";
1585 }
1586}
1587
John Stilesda5cdf62021-01-28 11:47:29 -05001588int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1589 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001590 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001591}
1592
1593int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1594 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001595 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001596}
1597
John Stiles569249b2020-11-03 12:18:22 -05001598bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001599 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001600 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001601 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001602 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001603 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001604 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001605 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001606 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001607 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001608 break;
1609 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001610 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001611 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001612 }
1613 this->write("(Inputs _in [[stage_in]]");
1614 if (-1 != fUniformBuffer) {
1615 this->write(", constant Uniforms& _uniforms [[buffer(" +
1616 to_string(fUniformBuffer) + ")]]");
1617 }
Brian Osman133724c2020-10-28 14:14:39 -04001618 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001619 if (e->is<GlobalVarDeclaration>()) {
1620 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001621 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1622 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1623 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001624 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001625 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001626 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001627 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001628 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001629 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001630 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001631 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001632 }
1633 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001634 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001635 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001636 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001637 this->write(")]]");
1638 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001639 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001640 this->write(SAMPLER_SUFFIX);
1641 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001642 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001643 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001644 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001645 } else if (e->is<InterfaceBlock>()) {
1646 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001647 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001648 continue;
1649 }
1650 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001651 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001652 this->write("& " );
1653 this->write(fInterfaceBlockNameMap[&intf]);
1654 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001655 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001656 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001657 }
1658 }
John Stiles270cec22021-02-17 12:59:36 -05001659 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001660 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001661 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001662 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001663 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001664 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001665 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001666 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001667 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001668 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001669 separator = ", ";
1670 } else {
John Stilesb4418502021-02-04 10:57:08 -05001671 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001672 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001673 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001674 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001675 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001676 }
John Stiles569249b2020-11-03 12:18:22 -05001677 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001678 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1679 continue;
1680 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001681 this->write(separator);
1682 separator = ", ";
Brian Osman58134e12021-05-13 14:51:07 -04001683 this->writeModifiers(param->modifiers());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001684 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001685 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001686 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001687 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001688 }
Timothy Liang651286f2018-06-07 09:55:33 -04001689 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001690 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001691 }
John Stiles569249b2020-11-03 12:18:22 -05001692 this->write(")");
1693 return true;
1694}
Ethan Nicholascc305772017-10-13 16:17:45 -04001695
John Stiles569249b2020-11-03 12:18:22 -05001696void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1697 this->writeFunctionDeclaration(f.declaration());
1698 this->writeLine(";");
1699}
1700
John Stiles986c7fb2020-12-01 14:44:56 -05001701static bool is_block_ending_with_return(const Statement* stmt) {
1702 // This function detects (potentially nested) blocks that end in a return statement.
1703 if (!stmt->is<Block>()) {
1704 return false;
1705 }
1706 const StatementArray& block = stmt->as<Block>().children();
1707 for (int index = block.count(); index--; ) {
1708 const Statement& stmt = *block[index];
1709 if (stmt.is<ReturnStatement>()) {
1710 return true;
1711 }
1712 if (stmt.is<Block>()) {
1713 return is_block_ending_with_return(&stmt);
1714 }
1715 if (!stmt.is<Nop>()) {
1716 break;
1717 }
1718 }
1719 return false;
1720}
1721
John Stiles569249b2020-11-03 12:18:22 -05001722void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001723 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001724
John Stiles569249b2020-11-03 12:18:22 -05001725 if (!this->writeFunctionDeclaration(f.declaration())) {
1726 return;
1727 }
1728
John Stiles986c7fb2020-12-01 14:44:56 -05001729 fCurrentFunction = &f.declaration();
1730 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1731
John Stiles569249b2020-11-03 12:18:22 -05001732 this->writeLine(" {");
1733
John Stilese8da4d22021-03-24 09:19:45 -04001734 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001735 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001736 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001737 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001738 }
John Stilesc67b3622020-05-28 17:53:13 -04001739
John Stiles95680232021-04-22 15:05:20 -04001740 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001741 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001742 {
1743 AutoOutputStream outputToBuffer(this, &buffer);
1744 fIndentation++;
1745 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1746 if (!stmt->isEmpty()) {
1747 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001748 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001749 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001750 }
John Stilese8da4d22021-03-24 09:19:45 -04001751 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001752 // If the main function doesn't end with a return, we need to synthesize one here.
1753 if (!is_block_ending_with_return(f.body().get())) {
1754 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001755 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001756 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001757 }
John Stiles44532372020-12-07 12:33:55 -05001758 fIndentation--;
1759 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001760 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 this->write(fFunctionHeader);
1762 this->write(buffer.str());
1763}
1764
Brian Osman58134e12021-05-13 14:51:07 -04001765void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1767 this->write("thread ");
1768 }
1769 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001770 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001771 }
1772}
1773
1774void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001775 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001776 return;
1777 }
Brian Osman58134e12021-05-13 14:51:07 -04001778 this->writeModifiers(intf.variable().modifiers());
Timothy Liangdc89f192018-06-13 09:20:31 -04001779 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001780 this->writeLine(intf.typeName() + " {");
1781 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001782 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001783 structType = &structType->componentType();
1784 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001785 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001786 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001787 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001788 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001789 }
1790 fIndentation--;
1791 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001792 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001793 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001794 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001795 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001796 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001797 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001798 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001799 } else if (intf.arraySize() == Type::kUnsizedArray){
1800 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001801 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001802 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001803 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001804 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001805 }
1806 this->writeLine(";");
1807}
1808
Timothy Liangdc89f192018-06-13 09:20:31 -04001809void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1810 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001811 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001812 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001813 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001814 int fieldOffset = field.fModifiers.fLayout.fOffset;
1815 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001816 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001817 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1818 return;
1819 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001820 if (fieldOffset != -1) {
1821 if (currentOffset > fieldOffset) {
1822 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001823 "offset of field '" + field.fName + "' must be at least " +
1824 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001825 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001826 } else if (currentOffset < fieldOffset) {
1827 this->write("char pad");
1828 this->write(to_string(fPaddingCount++));
1829 this->write("[");
1830 this->write(to_string(fieldOffset - currentOffset));
1831 this->writeLine("];");
1832 currentOffset = fieldOffset;
1833 }
1834 int alignment = memoryLayout.alignment(*fieldType);
1835 if (fieldOffset % alignment) {
1836 fErrors.error(parentOffset,
1837 "offset of field '" + field.fName + "' must be a multiple of " +
1838 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001839 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001840 }
1841 }
Brian Osman8609a242020-09-08 14:01:49 -04001842 size_t fieldSize = memoryLayout.size(*fieldType);
1843 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1844 fErrors.error(parentOffset, "field offset overflow");
1845 return;
1846 }
1847 currentOffset += fieldSize;
Brian Osman58134e12021-05-13 14:51:07 -04001848 this->writeModifiers(field.fModifiers);
John Stilesb4418502021-02-04 10:57:08 -05001849 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001850 this->write(" ");
1851 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001852 this->writeLine(";");
1853 if (parentIntf) {
1854 fInterfaceBlockMap[&field] = parentIntf;
1855 }
1856 }
1857}
1858
Ethan Nicholascc305772017-10-13 16:17:45 -04001859void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001860 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001861}
1862
Ethan Nicholasd2e09602021-06-10 11:21:59 -04001863void MetalCodeGenerator::writeName(StringFragment name) {
Timothy Liang651286f2018-06-07 09:55:33 -04001864 if (fReservedWords.find(name) != fReservedWords.end()) {
1865 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1866 }
1867 this->write(name);
1868}
1869
Brian Osman58134e12021-05-13 14:51:07 -04001870void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl) {
1871 this->writeModifiers(varDecl.var().modifiers());
John Stilesb4418502021-02-04 10:57:08 -05001872 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001873 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001874 this->writeName(varDecl.var().name());
1875 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001876 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001877 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001878 }
1879 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001880}
1881
1882void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001883 switch (s.kind()) {
1884 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001885 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001886 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001887 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001888 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001889 this->write(";");
1890 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001891 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001892 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001893 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001894 case Statement::Kind::kVarDeclaration:
Brian Osman58134e12021-05-13 14:51:07 -04001895 this->writeVarDeclaration(s.as<VarDeclaration>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001896 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001897 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001898 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001899 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001900 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001901 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001902 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001903 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001904 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001905 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001906 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001907 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001908 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001909 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001910 this->write("break;");
1911 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001912 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001913 this->write("continue;");
1914 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001915 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001916 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001917 break;
John Stiles98c1f822020-09-09 14:18:53 -04001918 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001919 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001920 this->write(";");
1921 break;
1922 default:
John Stileseada7bc2021-02-02 16:29:32 -05001923 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001924 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001925 }
1926}
1927
Ethan Nicholascc305772017-10-13 16:17:45 -04001928void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001929 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1930 // something here to make the code valid).
1931 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001932 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001933 this->writeLine("{");
1934 fIndentation++;
1935 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001936 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1937 if (!stmt->isEmpty()) {
1938 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001939 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001940 }
1941 }
1942 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001943 fIndentation--;
1944 this->write("}");
1945 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001946}
1947
1948void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1949 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001950 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001951 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001952 this->writeStatement(*stmt.ifTrue());
1953 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001954 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001955 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001956 }
1957}
1958
1959void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001960 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1961 if (!f.initializer() && f.test() && !f.next()) {
1962 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001963 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001964 this->write(") ");
1965 this->writeStatement(*f.statement());
1966 return;
1967 }
1968
John Stiles1a15e572021-04-19 14:57:15 -04001969 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001970 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04001971 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001972 } else {
John Stiles1a15e572021-04-19 14:57:15 -04001973 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001974 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001975 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001976 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001977 }
1978 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001979 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001980 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001981 }
1982 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001983 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001984}
1985
Ethan Nicholascc305772017-10-13 16:17:45 -04001986void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1987 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001988 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001989 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001990 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001991 this->write(");");
1992}
1993
1994void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1995 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001996 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001997 this->writeLine(") {");
1998 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001999 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
2000 const SwitchCase& c = stmt->as<SwitchCase>();
2001 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002002 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05002003 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002004 this->writeLine(":");
2005 } else {
2006 this->writeLine("default:");
2007 }
John Stilesb23a64b2021-03-11 08:27:59 -05002008 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05002009 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002010 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05002011 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05002012 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04002013 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002014 }
2015 fIndentation--;
2016 this->write("}");
2017}
2018
John Stiles986c7fb2020-12-01 14:44:56 -05002019void MetalCodeGenerator::writeReturnStatementFromMain() {
2020 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05002021 switch (fProgram.fConfig->fKind) {
Brian Salomon3e2fe2b2021-06-02 09:16:30 -04002022 case ProgramKind::kVertex:
John Stilesdbd4e6f2021-02-16 13:29:15 -05002023 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05002024 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05002025 break;
John Stiles986c7fb2020-12-01 14:44:56 -05002026 default:
2027 SkDEBUGFAIL("unsupported kind of program");
2028 }
2029}
2030
Ethan Nicholascc305772017-10-13 16:17:45 -04002031void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002032 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002033 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002034 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2035 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002036 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002037 this->writeLine(";");
2038 } else {
2039 fErrors.error(r.fOffset, "Metal does not support returning '" +
2040 r.expression()->type().description() + "' from main()");
2041 }
John Stiles986c7fb2020-12-01 14:44:56 -05002042 }
2043 this->writeReturnStatementFromMain();
2044 return;
2045 }
2046
Ethan Nicholascc305772017-10-13 16:17:45 -04002047 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002048 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002049 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002050 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002051 }
2052 this->write(";");
2053}
2054
Michael Ludwigbf58add2021-03-16 10:40:11 -04002055void MetalCodeGenerator::writeHeader() {
2056 this->write("#include <metal_stdlib>\n");
2057 this->write("#include <simd/simd.h>\n");
2058 this->write("using namespace metal;\n");
2059}
2060
Ethan Nicholascc305772017-10-13 16:17:45 -04002061void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002062 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002063 if (e->is<GlobalVarDeclaration>()) {
2064 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002065 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002066 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002067 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002068 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002069 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002070 if (-1 == fUniformBuffer) {
2071 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002072 fUniformBuffer = uniformSet;
2073 } else if (uniformSet != fUniformBuffer) {
2074 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
2075 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002076 }
2077 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002078 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002079 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002080 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002081 this->write(";\n");
2082 }
2083 }
2084 }
2085 if (-1 != fUniformBuffer) {
2086 this->write("};\n");
2087 }
2088}
2089
2090void MetalCodeGenerator::writeInputStruct() {
2091 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002092 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002093 if (e->is<GlobalVarDeclaration>()) {
2094 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002095 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002096 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2097 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002098 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002099 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002100 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002101 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002102 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002103 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002104 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002105 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002106 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002107 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002108 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002109 }
2110 }
2111 this->write(";\n");
2112 }
2113 }
2114 }
2115 this->write("};\n");
2116}
2117
2118void MetalCodeGenerator::writeOutputStruct() {
2119 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002120 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002121 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002122 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002123 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002124 }
Brian Osman133724c2020-10-28 14:14:39 -04002125 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002126 if (e->is<GlobalVarDeclaration>()) {
2127 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002128 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002129 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2130 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002131 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002132 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002133 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002134 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002135
2136 int location = var.modifiers().fLayout.fLocation;
2137 if (location < 0) {
2138 fErrors.error(var.fOffset,
2139 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002140 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002141 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002142 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002143 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002144 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002145 if (colorIndex) {
2146 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002147 }
Brian Osmanc0213602020-10-06 14:43:32 -04002148 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002149 }
2150 this->write(";\n");
2151 }
2152 }
Timothy Liang7d637782018-06-05 09:58:07 -04002153 }
John Stiles270cec22021-02-17 12:59:36 -05002154 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002155 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002156 }
2157 this->write("};\n");
2158}
2159
2160void MetalCodeGenerator::writeInterfaceBlocks() {
2161 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002162 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002163 if (e->is<InterfaceBlock>()) {
2164 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002165 wroteInterfaceBlock = true;
2166 }
2167 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002168 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002169 this->writeLine("struct sksl_synthetic_uniforms {");
2170 this->writeLine(" float u_skRTHeight;");
2171 this->writeLine("};");
2172 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002173}
2174
John Stilesdc75a972020-11-25 16:24:55 -05002175void MetalCodeGenerator::writeStructDefinitions() {
2176 for (const ProgramElement* e : fProgram.elements()) {
2177 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002178 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002179 }
2180 }
2181}
2182
John Stilescdcdb042020-07-06 09:03:51 -04002183void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2184 // Visit the interface blocks.
2185 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002186 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002187 }
Brian Osman133724c2020-10-28 14:14:39 -04002188 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002189 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002190 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002191 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002192 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2193 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2194 const Variable& var = decl.var();
Brian Osman58134e12021-05-13 14:51:07 -04002195 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2196 // Samplers are represented as a "texture/sampler" duo in the global struct.
2197 visitor->visitTexture(var.type(), var.name());
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002198 visitor->visitSampler(var.type(), var.name() + SAMPLER_SUFFIX);
Brian Osman58134e12021-05-13 14:51:07 -04002199 continue;
2200 }
2201
2202 if (!(var.modifiers().fFlags & ~Modifiers::kConst_Flag) &&
2203 -1 == var.modifiers().fLayout.fBuiltin) {
2204 // Visit a regular variable.
2205 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002206 }
2207 }
John Stilescdcdb042020-07-06 09:03:51 -04002208}
2209
2210void MetalCodeGenerator::writeGlobalStruct() {
2211 class : public GlobalStructVisitor {
2212 public:
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002213 void visitInterfaceBlock(const InterfaceBlock& block, StringFragment blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002214 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002215 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002216 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002217 fCodeGen->write("* ");
2218 fCodeGen->writeName(blockName);
2219 fCodeGen->write(";\n");
2220 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002221 void visitTexture(const Type& type, StringFragment name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002222 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002223 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002224 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002225 fCodeGen->write(" ");
2226 fCodeGen->writeName(name);
2227 fCodeGen->write(";\n");
2228 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002229 void visitSampler(const Type&, StringFragment name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002230 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002231 fCodeGen->write(" sampler ");
2232 fCodeGen->writeName(name);
2233 fCodeGen->write(";\n");
2234 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002235 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002236 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002237 fCodeGen->write(" ");
Brian Osman58134e12021-05-13 14:51:07 -04002238 fCodeGen->writeModifiers(var.modifiers());
John Stilesb4418502021-02-04 10:57:08 -05002239 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002240 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002241 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002242 fCodeGen->write(";\n");
2243 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002244 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002245 if (fFirst) {
2246 fCodeGen->write("struct Globals {\n");
2247 fFirst = false;
2248 }
2249 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002250 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002251 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002252 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002253 fFirst = true;
2254 }
2255 }
2256
2257 MetalCodeGenerator* fCodeGen = nullptr;
2258 bool fFirst = true;
2259 } visitor;
2260
2261 visitor.fCodeGen = this;
2262 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002263 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002264}
2265
2266void MetalCodeGenerator::writeGlobalInit() {
2267 class : public GlobalStructVisitor {
2268 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002269 void visitInterfaceBlock(const InterfaceBlock& blockType,
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002270 StringFragment blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002271 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002272 fCodeGen->write("&");
2273 fCodeGen->writeName(blockName);
2274 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002275 void visitTexture(const Type&, StringFragment name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002276 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002277 fCodeGen->writeName(name);
2278 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002279 void visitSampler(const Type&, StringFragment name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002280 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002281 fCodeGen->writeName(name);
2282 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002283 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002284 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002285 if (value) {
2286 fCodeGen->writeVarInitializer(var, *value);
2287 } else {
2288 fCodeGen->write("{}");
2289 }
2290 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002291 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002292 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002293 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002294 fFirst = false;
2295 } else {
2296 fCodeGen->write(", ");
2297 }
2298 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002299 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002300 if (!fFirst) {
2301 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002302 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002303 }
2304 }
2305 MetalCodeGenerator* fCodeGen = nullptr;
2306 bool fFirst = true;
2307 } visitor;
2308
2309 visitor.fCodeGen = this;
2310 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002311 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002312}
2313
Ethan Nicholascc305772017-10-13 16:17:45 -04002314void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002315 switch (e.kind()) {
2316 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002317 break;
Brian Osman58134e12021-05-13 14:51:07 -04002318 case ProgramElement::Kind::kGlobalVar:
Ethan Nicholascc305772017-10-13 16:17:45 -04002319 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002320 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002321 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002322 break;
John Stilesdc75a972020-11-25 16:24:55 -05002323 case ProgramElement::Kind::kStructDefinition:
2324 // Handled in writeStructDefinitions. Do nothing.
2325 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002326 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002327 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002328 break;
John Stiles569249b2020-11-03 12:18:22 -05002329 case ProgramElement::Kind::kFunctionPrototype:
2330 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2331 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002332 case ProgramElement::Kind::kModifiers:
Brian Osman58134e12021-05-13 14:51:07 -04002333 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers());
Ethan Nicholascc305772017-10-13 16:17:45 -04002334 this->writeLine(";");
2335 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002336 case ProgramElement::Kind::kEnum:
2337 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002338 default:
John Stileseada7bc2021-02-02 16:29:32 -05002339 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002340 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002341 }
2342}
2343
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002344MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2345 if (!e) {
2346 return kNo_Requirements;
2347 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002348 switch (e->kind()) {
2349 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002350 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002351 Requirements result = this->requirements(f.function());
2352 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002353 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002354 }
2355 return result;
2356 }
John Stiles8cad6372021-04-07 12:31:13 -04002357 case Expression::Kind::kConstructorCompound:
2358 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002359 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002360 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002361 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002362 case Expression::Kind::kConstructorSplat:
2363 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002364 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002365 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002366 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002367 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002368 }
2369 return result;
2370 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002371 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002372 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002373 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002374 return kGlobals_Requirement;
2375 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002376 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002377 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002378 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002379 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002380 case Expression::Kind::kBinary: {
2381 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002382 return this->requirements(bin.left().get()) |
2383 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002384 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002385 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002386 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002387 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002388 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002389 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002390 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002391 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002392 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002393 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002394 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002395 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2396 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002397 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002398 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002399 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002400 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002401 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002402 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002403 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002404 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002405 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002406 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002407 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002408 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002409 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002410 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002411 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002412 } else {
2413 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002414 }
2415 }
2416 return result;
2417 }
2418 default:
2419 return kNo_Requirements;
2420 }
2421}
2422
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002423MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2424 if (!s) {
2425 return kNo_Requirements;
2426 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002427 switch (s->kind()) {
2428 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002429 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002430 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002431 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002432 }
2433 return result;
2434 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002435 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002436 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002437 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002438 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002439 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002440 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002441 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002442 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002443 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002444 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002445 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002446 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002447 return this->requirements(i.test().get()) |
2448 this->requirements(i.ifTrue().get()) |
2449 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002450 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002451 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002452 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002453 return this->requirements(f.initializer().get()) |
2454 this->requirements(f.test().get()) |
2455 this->requirements(f.next().get()) |
2456 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002457 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002458 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002459 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002460 return this->requirements(d.test().get()) |
2461 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002462 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002463 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002464 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002465 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002466 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2467 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002468 }
2469 return result;
2470 }
2471 default:
2472 return kNo_Requirements;
2473 }
2474}
2475
2476MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002477 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002478 return kNo_Requirements;
2479 }
2480 auto found = fRequirements.find(&f);
2481 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002482 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002483 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002484 if (e->is<FunctionDefinition>()) {
2485 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002486 if (&def.declaration() == &f) {
2487 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002488 fRequirements[&f] = reqs;
2489 return reqs;
2490 }
2491 }
2492 }
John Stiles569249b2020-11-03 12:18:22 -05002493 // We never found a definition for this declared function, but it's legal to prototype a
2494 // function without ever giving a definition, as long as you don't call it.
2495 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002496 }
2497 return found->second;
2498}
2499
Timothy Liangb8eeb802018-07-23 16:46:16 -04002500bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002501 StringStream header;
2502 {
2503 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002504 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002505 this->writeStructDefinitions();
2506 this->writeUniformStruct();
2507 this->writeInputStruct();
2508 this->writeOutputStruct();
2509 this->writeInterfaceBlocks();
2510 this->writeGlobalStruct();
2511 }
2512 StringStream body;
2513 {
2514 AutoOutputStream outputToBody(this, &body, &fIndentation);
2515 for (const ProgramElement* e : fProgram.elements()) {
2516 this->writeProgramElement(*e);
2517 }
2518 }
2519 write_stringstream(header, *fOut);
2520 write_stringstream(fExtraFunctions, *fOut);
2521 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002522 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002523}
2524
John Stilesa6841be2020-08-06 14:11:56 -04002525} // namespace SkSL