blob: 2ba42f48feadb20aad739d706ed1244d18963989 [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
John Stiles7384b372021-04-01 13:48:15 -040013#include "src/sksl/ir/SkSLConstructorArray.h"
John Stilese3ae9682021-08-05 10:35:01 -040014#include "src/sksl/ir/SkSLConstructorArrayCast.h"
John Stiles8cad6372021-04-07 12:31:13 -040015#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stiles7384b372021-04-01 13:48:15 -040016#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040017#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040018#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040019#include "src/sksl/ir/SkSLConstructorStruct.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/sksl/ir/SkSLExpressionStatement.h"
21#include "src/sksl/ir/SkSLExtension.h"
22#include "src/sksl/ir/SkSLIndexExpression.h"
23#include "src/sksl/ir/SkSLModifiersDeclaration.h"
24#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050025#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050026#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040027
Brian Osmanc262a122020-08-06 16:34:34 -040028#include <algorithm>
29
Ethan Nicholascc305772017-10-13 16:17:45 -040030namespace SkSL {
31
John Stiles45990502021-02-16 10:55:27 -050032const char* MetalCodeGenerator::OperatorName(Operator op) {
33 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050034 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050035 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050036 }
37}
38
John Stilescdcdb042020-07-06 09:03:51 -040039class MetalCodeGenerator::GlobalStructVisitor {
40public:
41 virtual ~GlobalStructVisitor() = default;
Ethan Nicholas962dec42021-06-10 13:06:39 -040042 virtual void visitInterfaceBlock(const InterfaceBlock& block, skstd::string_view blockName) = 0;
43 virtual void visitTexture(const Type& type, skstd::string_view name) = 0;
44 virtual void visitSampler(const Type& type, skstd::string_view name) = 0;
John Stilesfdb8dbe2020-12-04 11:00:03 -050045 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040046};
47
Ethan Nicholas962dec42021-06-10 13:06:39 -040048void MetalCodeGenerator::write(skstd::string_view s) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -040049 if (s.empty()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040050 return;
51 }
52 if (fAtLineStart) {
53 for (int i = 0; i < fIndentation; i++) {
54 fOut->writeText(" ");
55 }
56 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -040057 fOut->writeText(String(s).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -040058 fAtLineStart = false;
59}
60
Ethan Nicholas962dec42021-06-10 13:06:39 -040061void MetalCodeGenerator::writeLine(skstd::string_view s) {
Ethan Nicholascc305772017-10-13 16:17:45 -040062 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050063 fOut->writeText(fLineEnding);
64 fAtLineStart = true;
65}
66
67void MetalCodeGenerator::finishLine() {
68 if (!fAtLineStart) {
69 this->writeLine();
70 }
Ethan Nicholascc305772017-10-13 16:17:45 -040071}
72
73void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040074 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040075}
76
Ethan Nicholas45fa8102020-01-13 10:58:49 -050077String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040078 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -050079 case Type::TypeKind::kArray:
80 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
81 return String::printf("array<%s, %d>",
82 this->typeName(type.componentType()).c_str(), type.columns());
83
Ethan Nicholase6592142020-09-08 10:22:09 -040084 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050085 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -050086
Ethan Nicholase6592142020-09-08 10:22:09 -040087 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050088 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
89 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -050090
Ethan Nicholase6592142020-09-08 10:22:09 -040091 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -050092 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -050093
Ethan Nicholascc305772017-10-13 16:17:45 -040094 default:
John Stiles7b2b8582021-08-09 14:20:54 -040095 // We currently only support full-precision types in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -050096 if (type == *fContext.fTypes.fHalf) {
John Stiles7b2b8582021-08-09 14:20:54 -040097 return "float";
Timothy Liang7d637782018-06-05 09:58:07 -040098 }
John Stiles7b2b8582021-08-09 14:20:54 -040099 if (type == *fContext.fTypes.fShort) {
100 return "int";
101 }
102 if (type == *fContext.fTypes.fUShort) {
103 return "uint";
104 }
105 return String(type.name());
Ethan Nicholascc305772017-10-13 16:17:45 -0400106 }
107}
108
Brian Osman02bc5222021-01-28 11:00:20 -0500109void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
110 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500111 this->writeLine("struct " + type.name() + " {");
112 fIndentation++;
113 this->writeFields(type.fields(), type.fOffset);
114 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500115 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500116}
117
John Stilesb4418502021-02-04 10:57:08 -0500118void MetalCodeGenerator::writeType(const Type& type) {
119 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500120}
121
Ethan Nicholascc305772017-10-13 16:17:45 -0400122void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (expr.kind()) {
124 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400125 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400126 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400127 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400128 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400129 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400130 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400131 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400132 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
133 break;
John Stilese3ae9682021-08-05 10:35:01 -0400134 case Expression::Kind::kConstructorArrayCast:
135 this->writeExpression(*expr.as<ConstructorArrayCast>().argument(), parentPrecedence);
136 break;
John Stiles8cad6372021-04-07 12:31:13 -0400137 case Expression::Kind::kConstructorCompound:
138 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400139 break;
140 case Expression::Kind::kConstructorDiagonalMatrix:
141 case Expression::Kind::kConstructorSplat:
142 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400143 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400144 case Expression::Kind::kConstructorMatrixResize:
145 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
146 parentPrecedence);
147 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400148 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400149 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400150 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400151 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400152 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400153 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400154 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400155 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400156 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400159 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400162 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400163 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400165 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400167 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400168 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400176 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400177 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400178 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400179 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400180 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400181 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400182 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400183 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400184 break;
185 default:
John Stileseada7bc2021-02-02 16:29:32 -0500186 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500187 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400188 }
189}
190
John Stiles06b84ef2020-12-09 12:35:48 -0500191String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
192 const ExpressionArray& arguments,
193 const SkTArray<VariableReference*>& outVars) {
194 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
195 const FunctionDeclaration& function = call.function();
196
John Stilese1068342021-03-22 11:57:41 -0400197 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
198 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500199 const char* separator = "";
200
201 // Emit a prototype for the function we'll be calling through to in our helper.
202 if (!function.isBuiltin()) {
203 this->writeFunctionDeclaration(function);
204 this->writeLine(";");
205 }
206
207 // Synthesize a helper function that takes the same inputs as `function`, except in places where
208 // `outVars` is non-null; in those places, we take the type of the VariableReference.
209 //
210 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500211 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500212 this->write(" ");
213 this->write(name);
214 this->write("(");
215 this->writeFunctionRequirementParams(function, separator);
216
217 SkASSERT(outVars.size() == arguments.size());
218 SkASSERT(outVars.size() == function.parameters().size());
219
John Stiles73e2c892021-02-13 13:58:01 -0500220 // We need to detect cases where the caller passes the same variable as an out-param more than
221 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
222 // redundant input parameter entirely, and not give it any name.)
223 std::unordered_set<const Variable*> writtenVars;
224
John Stiles06b84ef2020-12-09 12:35:48 -0500225 for (int index = 0; index < arguments.count(); ++index) {
226 this->write(separator);
227 separator = ", ";
228
229 const Variable* param = function.parameters()[index];
Brian Osman58134e12021-05-13 14:51:07 -0400230 this->writeModifiers(param->modifiers());
John Stiles06b84ef2020-12-09 12:35:48 -0500231
232 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500233 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500234
235 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
236 this->write("&");
237 }
238 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500239 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
240 if (didInsert) {
241 this->write(" ");
242 fIgnoreVariableReferenceModifiers = true;
243 this->writeVariableReference(*outVars[index]);
244 fIgnoreVariableReferenceModifiers = false;
245 }
John Stiles06b84ef2020-12-09 12:35:48 -0500246 } else {
247 this->write(" _var");
248 this->write(to_string(index));
249 }
John Stiles06b84ef2020-12-09 12:35:48 -0500250 }
251 this->writeLine(") {");
252
253 ++fIndentation;
254 for (int index = 0; index < outVars.count(); ++index) {
255 if (!outVars[index]) {
256 continue;
257 }
258 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500259 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500260 this->write(" _var");
261 this->write(to_string(index));
262
263 const Variable* param = function.parameters()[index];
264 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
265 this->write(" = ");
266 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500267 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500268 fIgnoreVariableReferenceModifiers = false;
269 }
270
271 this->writeLine(";");
272 }
273
John Stilesf7410bd2021-01-19 13:07:55 -0500274 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500275 bool hasResult = (call.type().name() != "void");
276 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500277 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500278 this->write(" _skResult = ");
279 }
280
John Stilese1068342021-03-22 11:57:41 -0400281 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500282 this->write("(");
283 separator = "";
284 this->writeFunctionRequirementArgs(function, separator);
285
286 for (int index = 0; index < arguments.count(); ++index) {
287 this->write(separator);
288 separator = ", ";
289
290 this->write("_var");
291 this->write(to_string(index));
292 }
293 this->writeLine(");");
294
295 for (int index = 0; index < outVars.count(); ++index) {
296 if (!outVars[index]) {
297 continue;
298 }
299 // outParam.zyx = _var2;
300 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500301 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500302 fIgnoreVariableReferenceModifiers = false;
303 this->write(" = _var");
304 this->write(to_string(index));
305 this->writeLine(";");
306 }
307
308 if (hasResult) {
309 this->writeLine("return _skResult;");
310 }
311
312 --fIndentation;
313 this->writeLine("}");
314
315 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500316}
317
John Stilesf64e4072020-12-10 10:34:27 -0500318String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
319 return "as_type<" + outType.displayName() + ">";
320}
321
Ethan Nicholascc305772017-10-13 16:17:45 -0400322void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400323 const FunctionDeclaration& function = c.function();
John Stiles496b7d12021-05-06 10:26:45 -0400324
325 // Many intrinsics need to be rewritten in Metal.
326 if (function.isIntrinsic()) {
327 if (this->writeIntrinsicCall(c, function.intrinsicKind())) {
John Stiles89ac7c22020-12-30 17:47:31 -0500328 return;
329 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400330 }
John Stilesb21fac22020-12-04 15:36:49 -0500331
John Stilesd7199b22020-12-30 16:22:58 -0500332 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
333 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
334 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
335 // allow a swizzle to be passed to a `floatN&`.)
336 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500337 const std::vector<const Variable*>& parameters = function.parameters();
338 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500339
340 bool foundOutParam = false;
341 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500342 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500343
344 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500345 // If this is an out parameter...
346 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500347 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500348 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500349 // Assignability was verified at IRGeneration time, so this should always succeed.
350 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
351 outVars[index] = info.fAssignedVar;
352 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500353 }
354 }
355
John Stiles06b84ef2020-12-09 12:35:48 -0500356 if (foundOutParam) {
357 // Out parameters need to be written back to at the end of the function. To do this, we
358 // synthesize a helper function which evaluates the out-param expression into a temporary
359 // variable, calls the original function, then writes the temp var back into the out param
360 // using the original out-param expression. (This lets us support things like swizzles and
361 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500362 this->write(getOutParamHelper(c, arguments, outVars));
363 } else {
John Stilese1068342021-03-22 11:57:41 -0400364 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500365 }
366
Ethan Nicholascc305772017-10-13 16:17:45 -0400367 this->write("(");
368 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500369 this->writeFunctionRequirementArgs(function, separator);
370 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400371 this->write(separator);
372 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500373
374 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500375 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500376 } else {
Brian Osman00185012021-02-04 16:07:11 -0500377 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500378 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400379 }
380 this->write(")");
381}
382
Brian Osman964f0a02020-12-29 10:15:22 -0500383static constexpr char kInverse2x2[] = R"(
384float2x2 float2x2_inverse(float2x2 m) {
385 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
386}
387)";
388
389static constexpr char kInverse3x3[] = R"(
390float3x3 float3x3_inverse(float3x3 m) {
391 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
392 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
393 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
394 float b01 = a22*a11 - a12*a21;
395 float b11 = -a22*a10 + a12*a20;
396 float b21 = a21*a10 - a11*a20;
397 float det = a00*b01 + a01*b11 + a02*b21;
398 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
399 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
400 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
401}
402)";
403
404static constexpr char kInverse4x4[] = R"(
405float4x4 float4x4_inverse(float4x4 m) {
406 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
407 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
408 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
409 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
410 float b00 = a00*a11 - a01*a10;
411 float b01 = a00*a12 - a02*a10;
412 float b02 = a00*a13 - a03*a10;
413 float b03 = a01*a12 - a02*a11;
414 float b04 = a01*a13 - a03*a11;
415 float b05 = a02*a13 - a03*a12;
416 float b06 = a20*a31 - a21*a30;
417 float b07 = a20*a32 - a22*a30;
418 float b08 = a20*a33 - a23*a30;
419 float b09 = a21*a32 - a22*a31;
420 float b10 = a21*a33 - a23*a31;
421 float b11 = a22*a33 - a23*a32;
422 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
423 return float4x4(a11*b11 - a12*b10 + a13*b09,
424 a02*b10 - a01*b11 - a03*b09,
425 a31*b05 - a32*b04 + a33*b03,
426 a22*b04 - a21*b05 - a23*b03,
427 a12*b08 - a10*b11 - a13*b07,
428 a00*b11 - a02*b08 + a03*b07,
429 a32*b02 - a30*b05 - a33*b01,
430 a20*b05 - a22*b02 + a23*b01,
431 a10*b10 - a11*b08 + a13*b06,
432 a01*b08 - a00*b10 - a03*b06,
433 a30*b04 - a31*b02 + a33*b00,
434 a21*b02 - a20*b04 - a23*b00,
435 a11*b07 - a10*b09 - a12*b06,
436 a00*b09 - a01*b07 + a02*b06,
437 a31*b01 - a30*b03 - a32*b00,
438 a20*b03 - a21*b01 + a22*b00) * (1/det);
439}
440)";
441
John Stilesd7199b22020-12-30 16:22:58 -0500442String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
443 // Only use polyfills for a function taking a single-argument square matrix.
444 if (arguments.size() == 1) {
445 const Type& type = arguments.front()->type();
446 if (type.isMatrix() && type.rows() == type.columns()) {
447 // Inject the correct polyfill based on the matrix size.
448 String name = this->typeName(type) + "_inverse";
449 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
450 if (didInsert) {
451 switch (type.rows()) {
452 case 2:
453 fExtraFunctions.writeText(kInverse2x2);
454 break;
455 case 3:
456 fExtraFunctions.writeText(kInverse3x3);
457 break;
458 case 4:
459 fExtraFunctions.writeText(kInverse4x4);
460 break;
461 }
462 }
463 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500464 }
465 }
John Stilesd7199b22020-12-30 16:22:58 -0500466 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
467 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500468}
469
Brian Osman93aed9a2020-12-28 15:18:46 -0500470static constexpr char kMatrixCompMult[] = R"(
471template <int C, int R>
472matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
473 matrix<float, C, R> result;
474 for (int c = 0; c < C; ++c) {
475 result[c] = a[c] * b[c];
476 }
477 return result;
478}
479)";
480
481void MetalCodeGenerator::writeMatrixCompMult() {
482 String name = "matrixCompMult";
483 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
484 fWrittenIntrinsics.insert(name);
485 fExtraFunctions.writeText(kMatrixCompMult);
486 }
487}
488
John Stiles86424eb2020-12-11 11:17:14 -0500489String MetalCodeGenerator::getTempVariable(const Type& type) {
490 String tempVar = "_skTemp" + to_string(fVarCount++);
491 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
492 return tempVar;
493}
494
John Stiles791c27d2020-12-30 14:56:57 -0500495void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
496 // Write out an intrinsic function call exactly as-is. No muss no fuss.
497 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500498 this->writeArgumentList(c.arguments());
499}
500
501void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500502 this->write("(");
503 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500504 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500505 this->write(separator);
506 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500507 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500508 }
509 this->write(")");
510}
511
John Stiles496b7d12021-05-06 10:26:45 -0400512bool MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400513 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400514 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400515 case k_sample_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500516 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400517 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500518 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400519 this->write(SAMPLER_SUFFIX);
520 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400521 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400522 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500523 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500524 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500525 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500526 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500527 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400528 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400529 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500530 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400531 this->write(")");
532 }
John Stiles496b7d12021-05-06 10:26:45 -0400533 return true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400534 }
John Stiles496b7d12021-05-06 10:26:45 -0400535 case k_mod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400536 // 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 -0500537 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500538 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500539 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500540 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500541 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500542 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500543 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
John Stiles496b7d12021-05-06 10:26:45 -0400544 return true;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500545 }
Brian Osman46787d52020-11-24 14:18:23 -0500546 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stiles496b7d12021-05-06 10:26:45 -0400547 case k_distance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500548 if (arguments[0]->type().columns() == 1) {
549 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500550 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500551 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500552 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500553 this->write(")");
554 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500555 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500556 }
John Stiles496b7d12021-05-06 10:26:45 -0400557 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500558 }
John Stiles496b7d12021-05-06 10:26:45 -0400559 case k_dot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500560 if (arguments[0]->type().columns() == 1) {
561 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500562 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500563 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500564 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500565 this->write(")");
566 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500567 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500568 }
John Stiles496b7d12021-05-06 10:26:45 -0400569 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500570 }
John Stiles496b7d12021-05-06 10:26:45 -0400571 case k_faceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500572 if (arguments[0]->type().columns() == 1) {
573 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
574 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500575 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500576 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500577 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500578 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500579 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500580 this->write("))");
581 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500582 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500583 }
John Stiles496b7d12021-05-06 10:26:45 -0400584 return true;
John Stilesad0571f2020-12-10 18:03:10 -0500585 }
John Stiles496b7d12021-05-06 10:26:45 -0400586 case k_length_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500587 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
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 case k_normalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500593 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500594 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500595 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400596 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500597 }
John Stiles496b7d12021-05-06 10:26:45 -0400598
599 case k_floatBitsToInt_IntrinsicKind:
600 case k_floatBitsToUint_IntrinsicKind:
601 case k_intBitsToFloat_IntrinsicKind:
602 case k_uintBitsToFloat_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500603 this->write(this->getBitcastIntrinsic(c.type()));
604 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500605 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500606 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400607 return true;
John Stiles0063a9f2020-12-10 18:01:45 -0500608 }
John Stiles496b7d12021-05-06 10:26:45 -0400609 case k_degrees_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(") * 57.2957795)");
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_radians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500616 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500617 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500618 this->write(") * 0.0174532925)");
John Stiles496b7d12021-05-06 10:26:45 -0400619 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500620 }
John Stiles496b7d12021-05-06 10:26:45 -0400621 case k_dFdx_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500622 this->write("dfdx");
623 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400624 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500625 }
John Stiles496b7d12021-05-06 10:26:45 -0400626 case k_dFdy_IntrinsicKind: {
Brian Salomond8d85b92021-07-07 09:41:17 -0400627 this->write(fRTFlipName + ".y*dfdy");
John Stilesd7199b22020-12-30 16:22:58 -0500628 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400629 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500630 }
John Stiles496b7d12021-05-06 10:26:45 -0400631 case k_inverse_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500632 this->write(this->getInversePolyfill(arguments));
633 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400634 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500635 }
John Stiles496b7d12021-05-06 10:26:45 -0400636 case k_inversesqrt_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500637 this->write("rsqrt");
638 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400639 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500640 }
John Stiles496b7d12021-05-06 10:26:45 -0400641 case k_atan_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500642 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
643 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400644 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500645 }
John Stiles496b7d12021-05-06 10:26:45 -0400646 case k_reflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500647 if (arguments[0]->type().columns() == 1) {
648 // We need to synthesize `I - 2 * N * I * N`.
649 String tmpI = this->getTempVariable(arguments[0]->type());
650 String tmpN = this->getTempVariable(arguments[1]->type());
651
652 // (_skTempI = ...
653 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500654 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500655
656 // , _skTempN = ...
657 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500658 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500659
660 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
661 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
662 } else {
663 this->writeSimpleIntrinsic(c);
664 }
John Stiles496b7d12021-05-06 10:26:45 -0400665 return true;
John Stiles791c27d2020-12-30 14:56:57 -0500666 }
John Stiles496b7d12021-05-06 10:26:45 -0400667 case k_refract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500668 if (arguments[0]->type().columns() == 1) {
669 // Metal does implement refract for vectors; rather than reimplementing refract from
670 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
671 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500672 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500673 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500674 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500675 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500676 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500677 this->write(").x)");
678 } else {
679 this->writeSimpleIntrinsic(c);
680 }
John Stiles496b7d12021-05-06 10:26:45 -0400681 return true;
John Stiles4b783d62020-12-30 14:58:07 -0500682 }
John Stiles496b7d12021-05-06 10:26:45 -0400683 case k_roundEven_IntrinsicKind: {
John Stiles23456532020-12-30 18:12:48 -0500684 this->write("rint");
685 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400686 return true;
John Stiles23456532020-12-30 18:12:48 -0500687 }
John Stiles496b7d12021-05-06 10:26:45 -0400688 case k_bitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500689 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500690 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500691 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400692 return true;
John Stilese7dc7cb2020-12-22 15:37:14 -0500693 }
John Stiles496b7d12021-05-06 10:26:45 -0400694 case k_findLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500695 // Create a temp variable to store the expression, to avoid double-evaluating it.
696 String skTemp = this->getTempVariable(arguments[0]->type());
697 String exprType = this->typeName(arguments[0]->type());
698
699 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
700 // Use select to detect zero inputs and force a -1 result.
701
702 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
703 this->write("(");
704 this->write(skTemp);
705 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500706 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500707 this->write("), select(ctz(");
708 this->write(skTemp);
709 this->write("), ");
710 this->write(exprType);
711 this->write("(-1), ");
712 this->write(skTemp);
713 this->write(" == ");
714 this->write(exprType);
715 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400716 return true;
John Stiles86424eb2020-12-11 11:17:14 -0500717 }
John Stiles496b7d12021-05-06 10:26:45 -0400718 case k_findMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500719 // Create a temp variable to store the expression, to avoid double-evaluating it.
720 String skTemp1 = this->getTempVariable(arguments[0]->type());
721 String exprType = this->typeName(arguments[0]->type());
722
723 // GLSL findMSB is actually quite different from Metal's clz:
724 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
725 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
726
727 // (_skTemp1 = (.....),
728 this->write("(");
729 this->write(skTemp1);
730 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500731 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500732 this->write("), ");
733
734 // Signed input types might be negative; we need another helper variable to negate the
735 // input (since we can only find one bits, not zero bits).
736 String skTemp2;
737 if (arguments[0]->type().isSigned()) {
738 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
739 skTemp2 = this->getTempVariable(arguments[0]->type());
740 this->write(skTemp2);
741 this->write(" = (select(");
742 this->write(skTemp1);
743 this->write(", ~");
744 this->write(skTemp1);
745 this->write(", ");
746 this->write(skTemp1);
747 this->write(" < 0)), ");
748 } else {
749 skTemp2 = skTemp1;
750 }
751
752 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
753 this->write("select(");
754 this->write(this->typeName(c.type()));
755 this->write("(clz(");
756 this->write(skTemp2);
757 this->write(")), ");
758 this->write(this->typeName(c.type()));
759 this->write("(-1), ");
760 this->write(skTemp2);
761 this->write(" == ");
762 this->write(exprType);
763 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400764 return true;
John Stiles9685e522020-12-14 11:52:14 -0500765 }
John Stiles496b7d12021-05-06 10:26:45 -0400766 case k_matrixCompMult_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500767 this->writeMatrixCompMult();
768 this->writeSimpleIntrinsic(c);
John Stiles496b7d12021-05-06 10:26:45 -0400769 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500770 }
John Stilescc2d9cc2021-07-09 17:38:41 -0400771 case k_mix_IntrinsicKind: {
772 SkASSERT(c.arguments().size() == 3);
773 if (arguments[2]->type().componentType().isBoolean()) {
774 // The Boolean forms of GLSL mix() use the select() intrinsic in Metal.
775 this->write("select");
776 this->writeArgumentList(c.arguments());
777 return true;
778 }
779 // The basic form of mix() is supported by Metal as-is.
780 this->writeSimpleIntrinsic(c);
781 return true;
782 }
John Stiles496b7d12021-05-06 10:26:45 -0400783 case k_equal_IntrinsicKind:
784 case k_greaterThan_IntrinsicKind:
785 case k_greaterThanEqual_IntrinsicKind:
786 case k_lessThan_IntrinsicKind:
787 case k_lessThanEqual_IntrinsicKind:
788 case k_notEqual_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500789 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500790 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500791 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400792 case k_equal_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500793 this->write(" == ");
794 break;
John Stiles496b7d12021-05-06 10:26:45 -0400795 case k_notEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500796 this->write(" != ");
797 break;
John Stiles496b7d12021-05-06 10:26:45 -0400798 case k_lessThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500799 this->write(" < ");
800 break;
John Stiles496b7d12021-05-06 10:26:45 -0400801 case k_lessThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500802 this->write(" <= ");
803 break;
John Stiles496b7d12021-05-06 10:26:45 -0400804 case k_greaterThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500805 this->write(" > ");
806 break;
John Stiles496b7d12021-05-06 10:26:45 -0400807 case k_greaterThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500808 this->write(" >= ");
809 break;
810 default:
John Stilesf57207b2021-02-02 17:50:34 -0500811 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500812 }
Brian Osman00185012021-02-04 16:07:11 -0500813 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500814 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400815 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500816 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400817 default:
John Stiles496b7d12021-05-06 10:26:45 -0400818 return false;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400819 }
820}
821
John Stilesfcf8cb22020-08-06 14:29:22 -0400822// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
823// Cells that don't exist in the source matrix will be populated with identity-matrix values.
824void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
825 SkASSERT(rows <= 4);
826 SkASSERT(columns <= 4);
827
828 const char* columnSeparator = "";
829 for (int c = 0; c < columns; ++c) {
830 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
831 columnSeparator = "), ";
832
833 // Determine how many values to take from the source matrix for this row.
834 int swizzleLength = 0;
835 if (c < sourceMatrix.columns()) {
836 swizzleLength = std::min<>(rows, sourceMatrix.rows());
837 }
838
839 // Emit all the values from the source matrix row.
840 bool firstItem;
841 switch (swizzleLength) {
842 case 0: firstItem = true; break;
843 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
844 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
845 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
846 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
847 default: SkUNREACHABLE;
848 }
849
850 // Emit the placeholder identity-matrix cells.
851 for (int r = swizzleLength; r < rows; ++r) {
852 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
853 firstItem = false;
854 }
855 }
856
857 fExtraFunctions.writeText(")");
858}
859
John Stiles1f7300b2021-07-08 15:40:38 -0400860// Assembles a matrix of type floatCxR by concatenating an arbitrary mix of values, named `x0`,
861// `x1`, etc. An error is written if the expression list don't contain exactly C*R scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400862void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles1f7300b2021-07-08 15:40:38 -0400863 int columns, int rows) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400864 size_t argIndex = 0;
865 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400866 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400867
John Stiles1f7300b2021-07-08 15:40:38 -0400868 const char* rowSeparator = "";
869 for (int r = 0; r < rows; ++r) {
870 fExtraFunctions.printf("%sfloat%d(", rowSeparator, rows);
871 rowSeparator = "), ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400872
John Stiles1f7300b2021-07-08 15:40:38 -0400873 const char* columnSeparator = "";
874 for (int c = 0; c < columns; ++c) {
875 fExtraFunctions.writeText(columnSeparator);
876 columnSeparator = ", ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400877
878 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400879 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400880 switch (argType.typeKind()) {
881 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400882 fExtraFunctions.printf("x%zu", argIndex);
883 break;
884 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400885 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400886 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
887 break;
888 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400889 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400890 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
891 argPosition / argType.rows(),
892 argPosition % argType.rows());
893 break;
894 }
895 default: {
896 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
897 fExtraFunctions.writeText("<error>");
898 break;
899 }
900 }
901
902 ++argPosition;
903 if (argPosition >= argType.columns() * argType.rows()) {
904 ++argIndex;
905 argPosition = 0;
906 }
907 } else {
908 SkDEBUGFAIL("not enough arguments for matrix constructor");
909 fExtraFunctions.writeText("<error>");
910 }
911 }
912 }
913
914 if (argPosition != 0 || argIndex != args.size()) {
915 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
916 fExtraFunctions.writeText(", <error>");
917 }
918
919 fExtraFunctions.writeText(")");
920}
921
John Stiles1bdafbf2020-05-28 12:17:20 -0400922// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
923// Keeps track of previously generated constructors so that we won't generate more than one
924// constructor for any given permutation of input argument types. Returns the name of the
925// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400926String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400927 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500928 int columns = matrix.columns();
929 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400930 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400931
932 // Create the helper-method name and use it as our lookup key.
933 String name;
934 name.appendf("float%dx%d_from", columns, rows);
935 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500936 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400937 }
938
939 // If a helper-method has already been synthesized, we don't need to synthesize it again.
940 auto [iter, newlyCreated] = fHelpers.insert(name);
941 if (!newlyCreated) {
942 return name;
943 }
944
945 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
946 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
947 // supply a mixture of scalars and vectors.)
948 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
949
950 size_t argIndex = 0;
951 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400952 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400953 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500954 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400955 argSeparator = ", ";
956 }
957
958 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
959
John Stiles9aeed132020-11-24 17:36:06 -0500960 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400961 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400962 } else {
John Stiles1f7300b2021-07-08 15:40:38 -0400963 this->assembleMatrixFromExpressions(c, columns, rows);
John Stiles1bdafbf2020-05-28 12:17:20 -0400964 }
965
John Stilesfcf8cb22020-08-06 14:29:22 -0400966 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500967 return name;
968}
969
970bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
971 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
972 return false;
973 }
974 if (t1.columns() > 1) {
975 return this->canCoerce(t1.componentType(), t2.componentType());
976 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500977 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500978}
979
John Stiles8cad6372021-04-07 12:31:13 -0400980bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -0400981 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -0400982
983 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
984 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
985 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
986 // scalars can be constructed trivially. In more complex cases, we generate a helper function
987 // that converts our inputs into a properly-shaped matrix.
988 // A matrix construct helper method is always used if any input argument is a matrix.
989 // Helper methods are also necessary when any argument would span multiple rows. For instance:
990 //
991 // float2 x = (1, 2);
992 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
993 // | 2 4 6 |
994 //
995 // float2 x = (2, 3);
996 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
997 // | 2 4 6 |
998 //
999 // float4 x = (1, 2, 3, 4);
1000 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1001 // | 2 4 |
1002 //
1003
1004 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001005 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001006 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001007 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001008 return true;
1009 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001010 position += expr->type().columns();
1011 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001012 // An input argument would span multiple rows; a helper function is required.
1013 return true;
1014 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001015 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001016 // We've advanced to the end of a row. Wrap to the start of the next row.
1017 position = 0;
1018 }
1019 }
1020
1021 return false;
1022}
1023
John Stiles5abb9e12021-04-06 13:47:19 -04001024void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1025 Precedence parentPrecedence) {
1026 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1027 // matrix-construct helper here.
1028 this->write(this->getMatrixConstructHelper(c));
1029 this->write("(");
1030 this->writeExpression(*c.argument(), Precedence::kSequence);
1031 this->write(")");
1032}
1033
John Stiles8cad6372021-04-07 12:31:13 -04001034void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1035 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001036 if (c.type().isVector()) {
1037 this->writeConstructorCompoundVector(c, parentPrecedence);
1038 } else if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001039 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001040 } else {
John Stiles6de2e1d2021-07-09 12:41:55 -04001041 fErrors.error(c.fOffset, "unsupported compound constructor");
John Stiles2bec8ab2021-04-06 18:40:04 -04001042 }
1043}
John Stiles7384b372021-04-01 13:48:15 -04001044
John Stiles6de2e1d2021-07-09 12:41:55 -04001045void MetalCodeGenerator::writeVectorFromMat2x2ConstructorHelper() {
1046 static constexpr char kCode[] =
1047R"(float4 float4_from_float2x2(float2x2 x) {
1048 return float4(x[0].xy, x[1].xy);
1049}
1050)";
1051
1052 String name = "matrixCompMult";
1053 if (fHelpers.find("float4_from_float2x2") == fHelpers.end()) {
1054 fHelpers.insert("float4_from_float2x2");
1055 fExtraFunctions.writeText(kCode);
1056 }
1057}
1058
1059void MetalCodeGenerator::writeConstructorCompoundVector(const ConstructorCompound& c,
1060 Precedence parentPrecedence) {
1061 SkASSERT(c.type().isVector());
1062
1063 // Metal supports constructing vectors from a mix of scalars and vectors, but not matrices.
1064 // GLSL supports vec4(mat2x2), so we detect that case here and emit a helper function.
1065 if (c.type().columns() == 4 && c.argumentSpan().size() == 1) {
1066 const Expression& expr = *c.argumentSpan().front();
1067 if (expr.type().isMatrix()) {
1068 SkASSERT(expr.type().rows() == 2);
1069 SkASSERT(expr.type().columns() == 2);
1070 this->writeVectorFromMat2x2ConstructorHelper();
1071 this->write("float4_from_float2x2(");
1072 this->writeExpression(expr, Precedence::kSequence);
1073 this->write(")");
1074 return;
1075 }
1076 }
1077
1078 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1079}
1080
John Stiles8cad6372021-04-07 12:31:13 -04001081void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1082 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001083 SkASSERT(c.type().isMatrix());
1084
John Stiles1bdafbf2020-05-28 12:17:20 -04001085 // Emit and invoke a matrix-constructor helper method if one is necessary.
1086 if (this->matrixConstructHelperIsNeeded(c)) {
1087 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001088 this->write("(");
1089 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001090 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001091 this->write(separator);
1092 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001093 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001094 }
John Stiles1fa15b12020-05-28 17:36:54 +00001095 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001096 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001097 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001098
John Stiles2bec8ab2021-04-06 18:40:04 -04001099 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1100 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1101 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1102 // can group our inputs up and synthesize a constructor for each column.
1103 const Type& matrixType = c.type();
1104 const Type& columnType = matrixType.componentType().toCompound(
1105 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1106
1107 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001108 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001109 const char* separator = "";
1110 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001111 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001112 this->write(separator);
1113 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001114 if (arg->type().columns() < matrixType.rows()) {
1115 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001116 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001117 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001118 this->write("(");
1119 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001120 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001121 }
Brian Osman00185012021-02-04 16:07:11 -05001122 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001123 if (scalarCount && scalarCount == matrixType.rows()) {
1124 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001125 this->write(")");
1126 scalarCount = 0;
1127 }
1128 }
John Stiles7384b372021-04-01 13:48:15 -04001129 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001130}
1131
John Stilesb14a8192021-04-05 11:40:46 -04001132void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1133 const char* leftBracket,
1134 const char* rightBracket,
1135 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001136 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001137 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001138 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001139 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001140 this->write(separator);
1141 separator = ", ";
1142 this->writeExpression(*arg, Precedence::kSequence);
1143 }
John Stilesb14a8192021-04-05 11:40:46 -04001144 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001145}
1146
John Stilesb14a8192021-04-05 11:40:46 -04001147void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1148 const char* leftBracket,
1149 const char* rightBracket,
1150 Precedence parentPrecedence) {
1151 // If the type is coercible, emit it directly without the cast.
1152 auto args = c.argumentSpan();
1153 if (args.size() == 1) {
1154 if (this->canCoerce(c.type(), args.front()->type())) {
1155 this->writeExpression(*args.front(), parentPrecedence);
1156 return;
1157 }
John Stilesfd7252f2021-04-04 22:24:40 -04001158 }
1159
John Stilesb14a8192021-04-05 11:40:46 -04001160 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001161}
1162
Ethan Nicholascc305772017-10-13 16:17:45 -04001163void MetalCodeGenerator::writeFragCoord() {
Brian Salomond8d85b92021-07-07 09:41:17 -04001164 SkASSERT(fRTFlipName.length());
1165 this->write("float4(_fragCoord.x, ");
1166 this->write(fRTFlipName.c_str());
1167 this->write(".x + ");
1168 this->write(fRTFlipName.c_str());
1169 this->write(".y * _fragCoord.y, 0.0, _fragCoord.w)");
Ethan Nicholascc305772017-10-13 16:17:45 -04001170}
1171
1172void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001173 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001174 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001175 // we're actually targeting the clones.
1176 if (fIgnoreVariableReferenceModifiers) {
1177 this->writeName(ref.variable()->name());
1178 return;
1179 }
1180
Ethan Nicholas78686922020-10-08 06:46:27 -04001181 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001182 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001183 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001184 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001185 case SK_FRAGCOORD_BUILTIN:
1186 this->writeFragCoord();
1187 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001188 case SK_VERTEXID_BUILTIN:
1189 this->write("sk_VertexID");
1190 break;
1191 case SK_INSTANCEID_BUILTIN:
1192 this->write("sk_InstanceID");
1193 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001194 case SK_CLOCKWISE_BUILTIN:
1195 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001196 // clockwise to match Skia convention.
Brian Salomond8d85b92021-07-07 09:41:17 -04001197 this->write("(" + fRTFlipName + ".y < 0 ? _frontFacing : !_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001198 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001199 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001200 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001201 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001202 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001203 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001204 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001205 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001206 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1207 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001208 this->write("_uniforms.");
1209 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001210 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001211 }
1212 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001213 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001214 }
1215}
1216
1217void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001218 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001219 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001220 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001221 this->write("]");
1222}
1223
1224void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001225 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1226 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001227 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001228 this->write(".");
1229 }
Timothy Liang7d637782018-06-05 09:58:07 -04001230 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001231 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001232 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001233 break;
1234 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001235 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001236 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001237 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001238 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001239 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001240 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1241 this->write("->");
1242 }
Timothy Liang651286f2018-06-07 09:55:33 -04001243 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001244 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 }
1246}
1247
1248void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001249 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001250 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001251 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001252 SkASSERT(c >= 0 && c <= 3);
1253 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001254 }
1255}
1256
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001257void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1258 const Type& result) {
John Stilesc985e142021-05-13 14:01:48 -04001259 SkASSERT(left.isMatrix());
1260 SkASSERT(right.isMatrix());
1261 SkASSERT(result.isMatrix());
1262 SkASSERT(left.rows() == right.rows());
1263 SkASSERT(left.columns() == right.columns());
1264 SkASSERT(left.rows() == result.rows());
1265 SkASSERT(left.columns() == result.columns());
1266
1267 String key = "Matrix *= " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001268
1269 auto [iter, wasInserted] = fHelpers.insert(key);
1270 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001271 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001272 " left = left * right;\n"
1273 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001274 "}\n",
1275 this->typeName(result).c_str(), this->typeName(left).c_str(),
1276 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001277 }
1278}
1279
John Stiles39346472021-04-29 14:39:35 -04001280void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1281 SkASSERT(left.isMatrix());
1282 SkASSERT(right.isMatrix());
1283 SkASSERT(left.rows() == right.rows());
1284 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001285
John Stilesc985e142021-05-13 14:01:48 -04001286 String key = "Matrix == " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001287
1288 auto [iter, wasInserted] = fHelpers.insert(key);
1289 if (wasInserted) {
1290 fExtraFunctions.printf(
1291 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001292 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001293 this->typeName(left).c_str(), this->typeName(right).c_str());
1294
John Stiles39346472021-04-29 14:39:35 -04001295 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001296 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001297 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1298 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001299 }
John Stiles39346472021-04-29 14:39:35 -04001300
1301 fExtraFunctions.printf(
1302 ";\n"
1303 "}\n"
1304 "thread bool operator!=(const %s left, const %s right) {\n"
1305 " return !(left == right);\n"
1306 "}\n",
1307 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001308 }
1309}
1310
John Stilesc985e142021-05-13 14:01:48 -04001311void MetalCodeGenerator::writeMatrixDivisionHelpers(const Type& type) {
1312 SkASSERT(type.isMatrix());
1313
1314 String key = "Matrix / " + this->typeName(type);
1315
1316 auto [iter, wasInserted] = fHelpers.insert(key);
1317 if (wasInserted) {
1318 String typeName = this->typeName(type);
1319
1320 fExtraFunctions.printf(
1321 "thread %s operator/(const %s left, const %s right) {\n"
1322 " return %s(",
1323 typeName.c_str(), typeName.c_str(), typeName.c_str(), typeName.c_str());
1324
1325 const char* separator = "";
1326 for (int index=0; index<type.columns(); ++index) {
1327 fExtraFunctions.printf("%sleft[%d] / right[%d]", separator, index, index);
1328 separator = ", ";
1329 }
1330
1331 fExtraFunctions.printf(");\n"
1332 "}\n"
1333 "thread %s& operator/=(thread %s& left, thread const %s& right) {\n"
1334 " left = left / right;\n"
1335 " return left;\n"
1336 "}\n",
1337 typeName.c_str(), typeName.c_str(), typeName.c_str());
1338 }
1339}
1340
John Stiles39346472021-04-29 14:39:35 -04001341void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1342 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001343
John Stiles39346472021-04-29 14:39:35 -04001344 // If the array's component type needs a helper as well, we need to emit that one first.
1345 this->writeEqualityHelpers(type.componentType(), type.componentType());
1346
1347 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1348 if (wasInserted) {
1349 fExtraFunctions.writeText(R"(
John Stilese3ae9682021-08-05 10:35:01 -04001350template <typename T1, typename T2, size_t N>
1351bool operator==(thread const array<T1, N>& left, thread const array<T2, N>& right) {
John Stiles39346472021-04-29 14:39:35 -04001352 for (size_t index = 0; index < N; ++index) {
John Stilesef9a1b62021-08-10 14:31:12 +00001353 if (!(left[index] == right[index])) {
John Stiles39346472021-04-29 14:39:35 -04001354 return false;
1355 }
1356 }
1357 return true;
1358}
1359
John Stilese3ae9682021-08-05 10:35:01 -04001360template <typename T1, typename T2, size_t N>
1361bool operator!=(thread const array<T1, N>& left, thread const array<T2, N>& right) {
John Stiles39346472021-04-29 14:39:35 -04001362 return !(left == right);
1363}
1364)");
1365 }
1366}
1367
1368void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1369 SkASSERT(type.isStruct());
1370 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001371
1372 auto [iter, wasInserted] = fHelpers.insert(key);
1373 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001374 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1375 for (const Type::Field& field : type.fields()) {
1376 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001377 }
John Stiles39346472021-04-29 14:39:35 -04001378
1379 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1380 // and GLSL but do not exist by default in Metal.
1381 fExtraFunctions.printf(
1382 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1383 " return ",
1384 this->typeName(type).c_str(),
1385 this->typeName(type).c_str());
1386
1387 const char* separator = "";
1388 for (const Type::Field& field : type.fields()) {
1389 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1390 separator,
1391 (int)field.fName.size(), field.fName.data(),
1392 (int)field.fName.size(), field.fName.data());
1393 separator = " &&\n ";
1394 }
1395 fExtraFunctions.printf(
1396 ";\n"
1397 "}\n"
1398 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1399 " return !(left == right);\n"
1400 "}\n",
1401 this->typeName(type).c_str(),
1402 this->typeName(type).c_str());
1403 }
1404}
1405
1406void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1407 if (leftType.isArray() && rightType.isArray()) {
1408 this->writeArrayEqualityHelpers(leftType);
1409 return;
1410 }
1411 if (leftType.isStruct() && rightType.isStruct()) {
1412 this->writeStructEqualityHelpers(leftType);
1413 return;
1414 }
1415 if (leftType.isMatrix() && rightType.isMatrix()) {
1416 this->writeMatrixEqualityHelpers(leftType, rightType);
1417 return;
John Stiles01cdf012021-02-10 09:53:41 -05001418 }
1419}
1420
John Stiles6b131292021-05-12 17:12:21 -04001421void MetalCodeGenerator::writeNumberAsMatrix(const Expression& expr, const Type& matrixType) {
1422 SkASSERT(expr.type().isNumber());
1423 SkASSERT(matrixType.isMatrix());
1424
1425 // Componentwise multiply the scalar against a matrix of the desired size which contains all 1s.
1426 this->write("(");
1427 this->writeType(matrixType);
1428 this->write("(");
1429
1430 const char* separator = "";
1431 for (int index = matrixType.slotCount(); index--;) {
1432 this->write(separator);
1433 this->write("1.0");
1434 separator = ", ";
1435 }
1436
1437 this->write(") * ");
1438 this->writeExpression(expr, Precedence::kMultiplicative);
1439 this->write(")");
1440}
1441
Ethan Nicholascc305772017-10-13 16:17:45 -04001442void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1443 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001444 const Expression& left = *b.left();
1445 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001446 const Type& leftType = left.type();
1447 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001448 Operator op = b.getOperator();
1449 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001450 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001451 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001452 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001453 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001454 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001455 this->write("all");
1456 needParens = true;
1457 }
1458 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001459 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001460 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001461 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001462 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001463 needParens = true;
1464 }
1465 break;
1466 default:
1467 break;
1468 }
John Stiles39346472021-04-29 14:39:35 -04001469 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1470 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001471 }
John Stilesc985e142021-05-13 14:01:48 -04001472 if (op.removeAssignment().kind() == Token::Kind::TK_SLASH &&
1473 ((leftType.isMatrix() && rightType.isMatrix()) ||
1474 (leftType.isScalar() && rightType.isMatrix()) ||
1475 (leftType.isMatrix() && rightType.isScalar()))) {
1476 this->writeMatrixDivisionHelpers(leftType.isMatrix() ? leftType : rightType);
1477 }
1478 if (needParens) {
1479 this->write("(");
1480 }
John Stiles6011bbc2021-05-19 22:56:18 -04001481 bool needMatrixSplatOnScalar = rightType.isMatrix() && leftType.isNumber() &&
1482 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001483 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1484 if (needMatrixSplatOnScalar) {
1485 this->writeNumberAsMatrix(left, rightType);
1486 } else {
1487 this->writeExpression(left, precedence);
1488 }
John Stiles45990502021-02-16 10:55:27 -05001489 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001490 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001491 // This doesn't compile in Metal:
1492 // float4 x = float4(1);
1493 // x.xy *= float2x2(...);
1494 // with the error message "non-const reference cannot bind to vector element",
1495 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1496 // as long as the LHS has no side effects, and hope for the best otherwise.
1497 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001498 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001499 this->write(" ");
John Stiles7cbe66b2021-05-12 17:01:23 -04001500 this->write(OperatorName(op.removeAssignment()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001501 this->write(" ");
1502 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001503 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001504 }
John Stiles6b131292021-05-12 17:12:21 -04001505
John Stiles6011bbc2021-05-19 22:56:18 -04001506 needMatrixSplatOnScalar = leftType.isMatrix() && rightType.isNumber() &&
1507 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001508 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1509 if (needMatrixSplatOnScalar) {
1510 this->writeNumberAsMatrix(right, leftType);
1511 } else {
1512 this->writeExpression(right, precedence);
1513 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001514 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001515 this->write(")");
1516 }
1517}
1518
1519void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1520 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001521 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001522 this->write("(");
1523 }
Brian Osman00185012021-02-04 16:07:11 -05001524 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001525 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001526 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001527 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001528 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1529 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001530 this->write(")");
1531 }
1532}
1533
1534void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1535 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001536 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001537 this->write("(");
1538 }
John Stilesd6449e92020-11-30 09:13:23 -05001539 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001540 this->writeExpression(*p.operand(), Precedence::kPrefix);
1541 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001542 this->write(")");
1543 }
1544}
1545
1546void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1547 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001548 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001549 this->write("(");
1550 }
Brian Osman00185012021-02-04 16:07:11 -05001551 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001552 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001553 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001554 this->write(")");
1555 }
1556}
1557
1558void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001559 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001560}
1561
1562void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001563 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001564 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001565 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001566 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001567 this->write(to_string(i.value() & 0xffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001568 } else {
John Stiles12739df2020-12-29 09:47:20 -05001569 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001570 }
1571}
1572
1573void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001574 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001575}
1576
1577void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001578 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001579}
1580
John Stiles06b84ef2020-12-09 12:35:48 -05001581void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1582 const char*& separator) {
1583 Requirements requirements = this->requirements(f);
1584 if (requirements & kInputs_Requirement) {
1585 this->write(separator);
1586 this->write("_in");
1587 separator = ", ";
1588 }
1589 if (requirements & kOutputs_Requirement) {
1590 this->write(separator);
1591 this->write("_out");
1592 separator = ", ";
1593 }
1594 if (requirements & kUniforms_Requirement) {
1595 this->write(separator);
1596 this->write("_uniforms");
1597 separator = ", ";
1598 }
1599 if (requirements & kGlobals_Requirement) {
1600 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001601 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001602 separator = ", ";
1603 }
1604 if (requirements & kFragCoord_Requirement) {
1605 this->write(separator);
1606 this->write("_fragCoord");
1607 separator = ", ";
1608 }
1609}
1610
1611void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1612 const char*& separator) {
1613 Requirements requirements = this->requirements(f);
1614 if (requirements & kInputs_Requirement) {
1615 this->write(separator);
1616 this->write("Inputs _in");
1617 separator = ", ";
1618 }
1619 if (requirements & kOutputs_Requirement) {
1620 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001621 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001622 separator = ", ";
1623 }
1624 if (requirements & kUniforms_Requirement) {
1625 this->write(separator);
1626 this->write("Uniforms _uniforms");
1627 separator = ", ";
1628 }
1629 if (requirements & kGlobals_Requirement) {
1630 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001631 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001632 separator = ", ";
1633 }
1634 if (requirements & kFragCoord_Requirement) {
1635 this->write(separator);
1636 this->write("float4 _fragCoord");
1637 separator = ", ";
1638 }
1639}
1640
John Stilesda5cdf62021-01-28 11:47:29 -05001641int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1642 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001643 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001644}
1645
1646int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1647 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001648 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001649}
1650
John Stiles569249b2020-11-03 12:18:22 -05001651bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001652 fRTFlipName = fProgram.fInputs.fUseFlipRTUniform
1653 ? "_globals._anonInterface0->" SKSL_RTFLIP_NAME
1654 : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001655 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001656 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001657 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001658 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001659 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001660 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001661 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001662 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001663 break;
1664 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001665 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001666 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001667 }
1668 this->write("(Inputs _in [[stage_in]]");
1669 if (-1 != fUniformBuffer) {
1670 this->write(", constant Uniforms& _uniforms [[buffer(" +
1671 to_string(fUniformBuffer) + ")]]");
1672 }
Brian Osman133724c2020-10-28 14:14:39 -04001673 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001674 if (e->is<GlobalVarDeclaration>()) {
1675 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001676 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1677 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1678 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001679 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001680 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001681 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001682 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001683 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001684 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001685 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001686 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001687 }
1688 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001689 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001690 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001691 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001692 this->write(")]]");
1693 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001694 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001695 this->write(SAMPLER_SUFFIX);
1696 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001697 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001698 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001699 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001700 } else if (e->is<InterfaceBlock>()) {
1701 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001702 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001703 continue;
1704 }
1705 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001706 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001707 this->write("& " );
1708 this->write(fInterfaceBlockNameMap[&intf]);
1709 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001710 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001711 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001712 }
1713 }
John Stiles270cec22021-02-17 12:59:36 -05001714 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001715 if (fProgram.fInputs.fUseFlipRTUniform && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001716 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Brian Salomond8d85b92021-07-07 09:41:17 -04001717 fRTFlipName = "_anonInterface0." SKSL_RTFLIP_NAME;
Timothy Liang5422f9a2018-08-10 10:57:55 -04001718 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001719 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001720 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001721 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001722 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001723 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001724 separator = ", ";
1725 } else {
John Stilesb4418502021-02-04 10:57:08 -05001726 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001727 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001728 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001729 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001730 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001731 }
John Stiles569249b2020-11-03 12:18:22 -05001732 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001733 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1734 continue;
1735 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001736 this->write(separator);
1737 separator = ", ";
Brian Osman58134e12021-05-13 14:51:07 -04001738 this->writeModifiers(param->modifiers());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001739 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001740 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001741 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001742 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001743 }
Timothy Liang651286f2018-06-07 09:55:33 -04001744 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001745 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001746 }
John Stiles569249b2020-11-03 12:18:22 -05001747 this->write(")");
1748 return true;
1749}
Ethan Nicholascc305772017-10-13 16:17:45 -04001750
John Stiles569249b2020-11-03 12:18:22 -05001751void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1752 this->writeFunctionDeclaration(f.declaration());
1753 this->writeLine(";");
1754}
1755
John Stiles986c7fb2020-12-01 14:44:56 -05001756static bool is_block_ending_with_return(const Statement* stmt) {
1757 // This function detects (potentially nested) blocks that end in a return statement.
1758 if (!stmt->is<Block>()) {
1759 return false;
1760 }
1761 const StatementArray& block = stmt->as<Block>().children();
1762 for (int index = block.count(); index--; ) {
John Stiles628777c2021-08-04 22:07:41 -04001763 stmt = block[index].get();
1764 if (stmt->is<ReturnStatement>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001765 return true;
1766 }
John Stiles628777c2021-08-04 22:07:41 -04001767 if (stmt->is<Block>()) {
1768 return is_block_ending_with_return(stmt);
John Stiles986c7fb2020-12-01 14:44:56 -05001769 }
John Stiles628777c2021-08-04 22:07:41 -04001770 if (!stmt->is<Nop>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001771 break;
1772 }
1773 }
1774 return false;
1775}
1776
John Stiles569249b2020-11-03 12:18:22 -05001777void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001778 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001779
John Stiles569249b2020-11-03 12:18:22 -05001780 if (!this->writeFunctionDeclaration(f.declaration())) {
1781 return;
1782 }
1783
John Stiles986c7fb2020-12-01 14:44:56 -05001784 fCurrentFunction = &f.declaration();
1785 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1786
John Stiles569249b2020-11-03 12:18:22 -05001787 this->writeLine(" {");
1788
John Stilese8da4d22021-03-24 09:19:45 -04001789 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001790 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001791 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001792 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001793 }
John Stilesc67b3622020-05-28 17:53:13 -04001794
John Stiles95680232021-04-22 15:05:20 -04001795 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001796 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001797 {
1798 AutoOutputStream outputToBuffer(this, &buffer);
1799 fIndentation++;
1800 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1801 if (!stmt->isEmpty()) {
1802 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001803 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001804 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001805 }
John Stilese8da4d22021-03-24 09:19:45 -04001806 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001807 // If the main function doesn't end with a return, we need to synthesize one here.
1808 if (!is_block_ending_with_return(f.body().get())) {
1809 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001810 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001811 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 }
John Stiles44532372020-12-07 12:33:55 -05001813 fIndentation--;
1814 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001815 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001816 this->write(fFunctionHeader);
1817 this->write(buffer.str());
1818}
1819
Brian Osman58134e12021-05-13 14:51:07 -04001820void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001821 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1822 this->write("thread ");
1823 }
1824 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001825 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001826 }
1827}
1828
1829void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001830 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001831 return;
1832 }
Brian Osman58134e12021-05-13 14:51:07 -04001833 this->writeModifiers(intf.variable().modifiers());
Timothy Liangdc89f192018-06-13 09:20:31 -04001834 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001835 this->writeLine(intf.typeName() + " {");
1836 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001837 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001838 structType = &structType->componentType();
1839 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001840 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001841 this->writeFields(structType->fields(), structType->fOffset, &intf);
Brian Salomond8d85b92021-07-07 09:41:17 -04001842 if (fProgram.fInputs.fUseFlipRTUniform) {
1843 this->writeLine("float2 " SKSL_RTFLIP_NAME ";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001844 }
1845 fIndentation--;
1846 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001847 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001849 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001850 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001851 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001852 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001853 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001854 } else if (intf.arraySize() == Type::kUnsizedArray){
1855 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001856 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001857 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001858 } else {
Ethan Nicholas3533ff12021-08-02 12:53:29 -04001859 fInterfaceBlockNameMap[&intf] = *fProgram.fSymbols->takeOwnershipOfString("_anonInterface" +
1860 to_string(fAnonInterfaceCount++));
Ethan Nicholascc305772017-10-13 16:17:45 -04001861 }
1862 this->writeLine(";");
1863}
1864
Timothy Liangdc89f192018-06-13 09:20:31 -04001865void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1866 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001867 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001868 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001869 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001870 int fieldOffset = field.fModifiers.fLayout.fOffset;
1871 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001872 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001873 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1874 return;
1875 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001876 if (fieldOffset != -1) {
1877 if (currentOffset > fieldOffset) {
1878 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001879 "offset of field '" + field.fName + "' must be at least " +
1880 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001881 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001882 } else if (currentOffset < fieldOffset) {
1883 this->write("char pad");
1884 this->write(to_string(fPaddingCount++));
1885 this->write("[");
1886 this->write(to_string(fieldOffset - currentOffset));
1887 this->writeLine("];");
1888 currentOffset = fieldOffset;
1889 }
1890 int alignment = memoryLayout.alignment(*fieldType);
1891 if (fieldOffset % alignment) {
1892 fErrors.error(parentOffset,
1893 "offset of field '" + field.fName + "' must be a multiple of " +
1894 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001895 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001896 }
1897 }
Brian Osman8609a242020-09-08 14:01:49 -04001898 size_t fieldSize = memoryLayout.size(*fieldType);
1899 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1900 fErrors.error(parentOffset, "field offset overflow");
1901 return;
1902 }
1903 currentOffset += fieldSize;
Brian Osman58134e12021-05-13 14:51:07 -04001904 this->writeModifiers(field.fModifiers);
John Stilesb4418502021-02-04 10:57:08 -05001905 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001906 this->write(" ");
1907 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001908 this->writeLine(";");
1909 if (parentIntf) {
1910 fInterfaceBlockMap[&field] = parentIntf;
1911 }
1912 }
1913}
1914
Ethan Nicholascc305772017-10-13 16:17:45 -04001915void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001916 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001917}
1918
Ethan Nicholas962dec42021-06-10 13:06:39 -04001919void MetalCodeGenerator::writeName(skstd::string_view name) {
Timothy Liang651286f2018-06-07 09:55:33 -04001920 if (fReservedWords.find(name) != fReservedWords.end()) {
1921 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1922 }
1923 this->write(name);
1924}
1925
Brian Osman58134e12021-05-13 14:51:07 -04001926void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl) {
1927 this->writeModifiers(varDecl.var().modifiers());
John Stilesb4418502021-02-04 10:57:08 -05001928 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001929 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001930 this->writeName(varDecl.var().name());
1931 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001932 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001933 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001934 }
1935 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001936}
1937
1938void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001939 switch (s.kind()) {
1940 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001941 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001942 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001943 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001944 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001945 this->write(";");
1946 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001947 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001948 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001949 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001950 case Statement::Kind::kVarDeclaration:
Brian Osman58134e12021-05-13 14:51:07 -04001951 this->writeVarDeclaration(s.as<VarDeclaration>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001952 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001953 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001954 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001955 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001956 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001957 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001958 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001959 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001960 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001961 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001962 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001963 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001964 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001965 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001966 this->write("break;");
1967 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001968 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001969 this->write("continue;");
1970 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001971 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001972 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001973 break;
John Stiles98c1f822020-09-09 14:18:53 -04001974 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001975 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001976 this->write(";");
1977 break;
1978 default:
John Stileseada7bc2021-02-02 16:29:32 -05001979 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001980 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001981 }
1982}
1983
Ethan Nicholascc305772017-10-13 16:17:45 -04001984void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001985 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1986 // something here to make the code valid).
1987 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001988 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001989 this->writeLine("{");
1990 fIndentation++;
1991 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001992 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1993 if (!stmt->isEmpty()) {
1994 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001995 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001996 }
1997 }
1998 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001999 fIndentation--;
2000 this->write("}");
2001 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002002}
2003
2004void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
2005 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05002006 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002007 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002008 this->writeStatement(*stmt.ifTrue());
2009 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002010 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002011 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04002012 }
2013}
2014
2015void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05002016 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
2017 if (!f.initializer() && f.test() && !f.next()) {
2018 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05002019 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05002020 this->write(") ");
2021 this->writeStatement(*f.statement());
2022 return;
2023 }
2024
John Stiles1a15e572021-04-19 14:57:15 -04002025 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002026 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04002027 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04002028 } else {
John Stiles1a15e572021-04-19 14:57:15 -04002029 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04002030 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002031 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05002032 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002033 }
2034 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002035 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05002036 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002037 }
2038 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002039 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002040}
2041
Ethan Nicholascc305772017-10-13 16:17:45 -04002042void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
2043 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002044 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002045 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05002046 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002047 this->write(");");
2048}
2049
2050void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
2051 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05002052 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002053 this->writeLine(") {");
2054 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002055 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
2056 const SwitchCase& c = stmt->as<SwitchCase>();
2057 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002058 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05002059 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002060 this->writeLine(":");
2061 } else {
2062 this->writeLine("default:");
2063 }
John Stilesb23a64b2021-03-11 08:27:59 -05002064 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05002065 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002066 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05002067 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05002068 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04002069 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002070 }
2071 fIndentation--;
2072 this->write("}");
2073}
2074
John Stiles986c7fb2020-12-01 14:44:56 -05002075void MetalCodeGenerator::writeReturnStatementFromMain() {
2076 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05002077 switch (fProgram.fConfig->fKind) {
Brian Salomon3e2fe2b2021-06-02 09:16:30 -04002078 case ProgramKind::kVertex:
John Stilesdbd4e6f2021-02-16 13:29:15 -05002079 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05002080 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05002081 break;
John Stiles986c7fb2020-12-01 14:44:56 -05002082 default:
2083 SkDEBUGFAIL("unsupported kind of program");
2084 }
2085}
2086
Ethan Nicholascc305772017-10-13 16:17:45 -04002087void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002088 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002089 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002090 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2091 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002092 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002093 this->writeLine(";");
2094 } else {
2095 fErrors.error(r.fOffset, "Metal does not support returning '" +
2096 r.expression()->type().description() + "' from main()");
2097 }
John Stiles986c7fb2020-12-01 14:44:56 -05002098 }
2099 this->writeReturnStatementFromMain();
2100 return;
2101 }
2102
Ethan Nicholascc305772017-10-13 16:17:45 -04002103 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002104 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002105 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002106 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002107 }
2108 this->write(";");
2109}
2110
Michael Ludwigbf58add2021-03-16 10:40:11 -04002111void MetalCodeGenerator::writeHeader() {
2112 this->write("#include <metal_stdlib>\n");
2113 this->write("#include <simd/simd.h>\n");
2114 this->write("using namespace metal;\n");
2115}
2116
Ethan Nicholascc305772017-10-13 16:17:45 -04002117void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002118 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002119 if (e->is<GlobalVarDeclaration>()) {
2120 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002121 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002122 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002123 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002124 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002125 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002126 if (-1 == fUniformBuffer) {
2127 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002128 fUniformBuffer = uniformSet;
2129 } else if (uniformSet != fUniformBuffer) {
2130 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
2131 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002132 }
2133 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002134 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002135 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002136 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002137 this->write(";\n");
2138 }
2139 }
2140 }
2141 if (-1 != fUniformBuffer) {
2142 this->write("};\n");
2143 }
2144}
2145
2146void MetalCodeGenerator::writeInputStruct() {
2147 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002148 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002149 if (e->is<GlobalVarDeclaration>()) {
2150 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002151 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002152 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2153 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002154 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002155 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002156 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002157 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002158 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002159 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002160 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002161 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002162 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002163 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002164 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002165 }
2166 }
2167 this->write(";\n");
2168 }
2169 }
2170 }
2171 this->write("};\n");
2172}
2173
2174void MetalCodeGenerator::writeOutputStruct() {
2175 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002176 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002177 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002178 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002179 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002180 }
Brian Osman133724c2020-10-28 14:14:39 -04002181 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002182 if (e->is<GlobalVarDeclaration>()) {
2183 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002184 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002185 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2186 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002187 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002188 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002189 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002190 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002191
2192 int location = var.modifiers().fLayout.fLocation;
2193 if (location < 0) {
2194 fErrors.error(var.fOffset,
2195 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002196 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002197 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002198 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002199 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002200 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002201 if (colorIndex) {
2202 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002203 }
Brian Osmanc0213602020-10-06 14:43:32 -04002204 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002205 }
2206 this->write(";\n");
2207 }
2208 }
Timothy Liang7d637782018-06-05 09:58:07 -04002209 }
John Stiles270cec22021-02-17 12:59:36 -05002210 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002211 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002212 }
2213 this->write("};\n");
2214}
2215
2216void MetalCodeGenerator::writeInterfaceBlocks() {
2217 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002218 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002219 if (e->is<InterfaceBlock>()) {
2220 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002221 wroteInterfaceBlock = true;
2222 }
2223 }
Brian Salomond8d85b92021-07-07 09:41:17 -04002224 if (!wroteInterfaceBlock && fProgram.fInputs.fUseFlipRTUniform) {
Timothy Liang7d637782018-06-05 09:58:07 -04002225 this->writeLine("struct sksl_synthetic_uniforms {");
Brian Salomond8d85b92021-07-07 09:41:17 -04002226 this->writeLine(" float2 " SKSL_RTFLIP_NAME ";");
Timothy Liang7d637782018-06-05 09:58:07 -04002227 this->writeLine("};");
2228 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002229}
2230
John Stilesdc75a972020-11-25 16:24:55 -05002231void MetalCodeGenerator::writeStructDefinitions() {
2232 for (const ProgramElement* e : fProgram.elements()) {
2233 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002234 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002235 }
2236 }
2237}
2238
John Stilescdcdb042020-07-06 09:03:51 -04002239void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2240 // Visit the interface blocks.
2241 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002242 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002243 }
Brian Osman133724c2020-10-28 14:14:39 -04002244 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002245 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002246 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002247 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002248 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2249 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2250 const Variable& var = decl.var();
Brian Osman58134e12021-05-13 14:51:07 -04002251 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2252 // Samplers are represented as a "texture/sampler" duo in the global struct.
2253 visitor->visitTexture(var.type(), var.name());
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002254 visitor->visitSampler(var.type(), var.name() + SAMPLER_SUFFIX);
Brian Osman58134e12021-05-13 14:51:07 -04002255 continue;
2256 }
2257
2258 if (!(var.modifiers().fFlags & ~Modifiers::kConst_Flag) &&
2259 -1 == var.modifiers().fLayout.fBuiltin) {
2260 // Visit a regular variable.
2261 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002262 }
2263 }
John Stilescdcdb042020-07-06 09:03:51 -04002264}
2265
2266void MetalCodeGenerator::writeGlobalStruct() {
2267 class : public GlobalStructVisitor {
2268 public:
Ethan Nicholas962dec42021-06-10 13:06:39 -04002269 void visitInterfaceBlock(const InterfaceBlock& block,
2270 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002271 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002272 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002273 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002274 fCodeGen->write("* ");
2275 fCodeGen->writeName(blockName);
2276 fCodeGen->write(";\n");
2277 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002278 void visitTexture(const Type& type, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002279 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002280 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002281 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002282 fCodeGen->write(" ");
2283 fCodeGen->writeName(name);
2284 fCodeGen->write(";\n");
2285 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002286 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002287 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002288 fCodeGen->write(" sampler ");
2289 fCodeGen->writeName(name);
2290 fCodeGen->write(";\n");
2291 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002292 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002293 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002294 fCodeGen->write(" ");
Brian Osman58134e12021-05-13 14:51:07 -04002295 fCodeGen->writeModifiers(var.modifiers());
John Stilesb4418502021-02-04 10:57:08 -05002296 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002297 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002298 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002299 fCodeGen->write(";\n");
2300 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002301 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002302 if (fFirst) {
2303 fCodeGen->write("struct Globals {\n");
2304 fFirst = false;
2305 }
2306 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002307 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002308 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002309 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002310 fFirst = true;
2311 }
2312 }
2313
2314 MetalCodeGenerator* fCodeGen = nullptr;
2315 bool fFirst = true;
2316 } visitor;
2317
2318 visitor.fCodeGen = this;
2319 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002320 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002321}
2322
2323void MetalCodeGenerator::writeGlobalInit() {
2324 class : public GlobalStructVisitor {
2325 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002326 void visitInterfaceBlock(const InterfaceBlock& blockType,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002327 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002328 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002329 fCodeGen->write("&");
2330 fCodeGen->writeName(blockName);
2331 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002332 void visitTexture(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002333 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002334 fCodeGen->writeName(name);
2335 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002336 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002337 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002338 fCodeGen->writeName(name);
2339 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002340 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002341 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002342 if (value) {
2343 fCodeGen->writeVarInitializer(var, *value);
2344 } else {
2345 fCodeGen->write("{}");
2346 }
2347 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002348 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002349 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002350 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002351 fFirst = false;
2352 } else {
2353 fCodeGen->write(", ");
2354 }
2355 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002356 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002357 if (!fFirst) {
2358 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002359 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002360 }
2361 }
2362 MetalCodeGenerator* fCodeGen = nullptr;
2363 bool fFirst = true;
2364 } visitor;
2365
2366 visitor.fCodeGen = this;
2367 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002368 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002369}
2370
Ethan Nicholascc305772017-10-13 16:17:45 -04002371void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002372 switch (e.kind()) {
2373 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002374 break;
Brian Osman58134e12021-05-13 14:51:07 -04002375 case ProgramElement::Kind::kGlobalVar:
Ethan Nicholascc305772017-10-13 16:17:45 -04002376 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002377 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002378 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002379 break;
John Stilesdc75a972020-11-25 16:24:55 -05002380 case ProgramElement::Kind::kStructDefinition:
2381 // Handled in writeStructDefinitions. Do nothing.
2382 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002383 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002384 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002385 break;
John Stiles569249b2020-11-03 12:18:22 -05002386 case ProgramElement::Kind::kFunctionPrototype:
2387 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2388 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002389 case ProgramElement::Kind::kModifiers:
Brian Osman58134e12021-05-13 14:51:07 -04002390 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers());
Ethan Nicholascc305772017-10-13 16:17:45 -04002391 this->writeLine(";");
2392 break;
2393 default:
John Stileseada7bc2021-02-02 16:29:32 -05002394 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002395 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002396 }
2397}
2398
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002399MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2400 if (!e) {
2401 return kNo_Requirements;
2402 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002403 switch (e->kind()) {
2404 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002405 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002406 Requirements result = this->requirements(f.function());
2407 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002408 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002409 }
2410 return result;
2411 }
John Stiles8cad6372021-04-07 12:31:13 -04002412 case Expression::Kind::kConstructorCompound:
2413 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002414 case Expression::Kind::kConstructorArray:
John Stilese3ae9682021-08-05 10:35:01 -04002415 case Expression::Kind::kConstructorArrayCast:
John Stiles2938eea2021-04-01 18:58:25 -04002416 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002417 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002418 case Expression::Kind::kConstructorSplat:
2419 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002420 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002421 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002422 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002423 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002424 }
2425 return result;
2426 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002427 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002428 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002429 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002430 return kGlobals_Requirement;
2431 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002432 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002433 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002434 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002435 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002436 case Expression::Kind::kBinary: {
2437 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002438 return this->requirements(bin.left().get()) |
2439 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002440 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002441 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002442 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002443 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002444 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002445 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002446 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002447 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002448 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002449 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002450 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002451 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2452 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002453 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002454 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002455 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002456 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002457 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002458 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002459 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002460 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002461 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002462 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002463 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002464 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002465 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002466 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002467 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002468 } else {
2469 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002470 }
2471 }
2472 return result;
2473 }
2474 default:
2475 return kNo_Requirements;
2476 }
2477}
2478
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002479MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2480 if (!s) {
2481 return kNo_Requirements;
2482 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002483 switch (s->kind()) {
2484 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002485 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002486 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002487 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002488 }
2489 return result;
2490 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002491 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002492 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002493 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002494 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002495 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002496 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002497 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002498 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002499 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002500 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002501 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002502 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002503 return this->requirements(i.test().get()) |
2504 this->requirements(i.ifTrue().get()) |
2505 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002506 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002507 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002508 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002509 return this->requirements(f.initializer().get()) |
2510 this->requirements(f.test().get()) |
2511 this->requirements(f.next().get()) |
2512 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002513 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002514 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002515 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002516 return this->requirements(d.test().get()) |
2517 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002518 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002519 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002520 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002521 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002522 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2523 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002524 }
2525 return result;
2526 }
2527 default:
2528 return kNo_Requirements;
2529 }
2530}
2531
2532MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002533 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002534 return kNo_Requirements;
2535 }
2536 auto found = fRequirements.find(&f);
2537 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002538 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002539 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002540 if (e->is<FunctionDefinition>()) {
2541 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002542 if (&def.declaration() == &f) {
2543 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002544 fRequirements[&f] = reqs;
2545 return reqs;
2546 }
2547 }
2548 }
John Stiles569249b2020-11-03 12:18:22 -05002549 // We never found a definition for this declared function, but it's legal to prototype a
2550 // function without ever giving a definition, as long as you don't call it.
2551 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002552 }
2553 return found->second;
2554}
2555
Timothy Liangb8eeb802018-07-23 16:46:16 -04002556bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002557 StringStream header;
2558 {
2559 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002560 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002561 this->writeStructDefinitions();
2562 this->writeUniformStruct();
2563 this->writeInputStruct();
2564 this->writeOutputStruct();
2565 this->writeInterfaceBlocks();
2566 this->writeGlobalStruct();
2567 }
2568 StringStream body;
2569 {
2570 AutoOutputStream outputToBody(this, &body, &fIndentation);
2571 for (const ProgramElement* e : fProgram.elements()) {
2572 this->writeProgramElement(*e);
2573 }
2574 }
2575 write_stringstream(header, *fOut);
2576 write_stringstream(fExtraFunctions, *fOut);
2577 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002578 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002579}
2580
John Stilesa6841be2020-08-06 14:11:56 -04002581} // namespace SkSL