blob: 3c4f2e6a8f7e051e6e347e23e3e8982a94f96d8a [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/ir/SkSLExpressionStatement.h"
14#include "src/sksl/ir/SkSLExtension.h"
15#include "src/sksl/ir/SkSLIndexExpression.h"
16#include "src/sksl/ir/SkSLModifiersDeclaration.h"
17#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050018#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040020
Brian Osmanc262a122020-08-06 16:34:34 -040021#include <algorithm>
22
Ethan Nicholascc305772017-10-13 16:17:45 -040023namespace SkSL {
24
John Stiles45990502021-02-16 10:55:27 -050025const char* MetalCodeGenerator::OperatorName(Operator op) {
26 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050027 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050028 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050029 }
30}
31
John Stilescdcdb042020-07-06 09:03:51 -040032class MetalCodeGenerator::GlobalStructVisitor {
33public:
34 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050035 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
36 virtual void visitTexture(const Type& type, const String& name) = 0;
37 virtual void visitSampler(const Type& type, const String& name) = 0;
38 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040039};
40
Timothy Liangee84fe12018-05-18 14:38:19 -040041void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050042 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
43 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
44 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
45 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
46 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
47 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
48 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
49 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
50 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
51 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
52 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
53 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
54 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
55 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
56 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
57 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
58 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
59 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
60 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
61 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
62 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
63 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
64 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
65 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
66 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
67 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
68 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
69 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
70 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050071 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050072 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040073}
74
Ethan Nicholascc305772017-10-13 16:17:45 -040075void MetalCodeGenerator::write(const char* s) {
76 if (!s[0]) {
77 return;
78 }
79 if (fAtLineStart) {
80 for (int i = 0; i < fIndentation; i++) {
81 fOut->writeText(" ");
82 }
83 }
84 fOut->writeText(s);
85 fAtLineStart = false;
86}
87
88void MetalCodeGenerator::writeLine(const char* s) {
89 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050090 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040091}
92
93void MetalCodeGenerator::write(const String& s) {
94 this->write(s.c_str());
95}
96
97void MetalCodeGenerator::writeLine(const String& s) {
98 this->writeLine(s.c_str());
99}
100
101void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500102 fOut->writeText(fLineEnding);
103 fAtLineStart = true;
104}
105
106void MetalCodeGenerator::finishLine() {
107 if (!fAtLineStart) {
108 this->writeLine();
109 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400110}
111
112void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400113 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400114}
115
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500116String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400117 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500118 case Type::TypeKind::kArray:
119 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
120 return String::printf("array<%s, %d>",
121 this->typeName(type.componentType()).c_str(), type.columns());
122
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500124 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500125
Ethan Nicholase6592142020-09-08 10:22:09 -0400126 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500127 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
128 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500129
Ethan Nicholase6592142020-09-08 10:22:09 -0400130 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500131 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500132
John Stilesfd41d872020-11-25 22:39:45 -0500133 case Type::TypeKind::kEnum:
134 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500135
Ethan Nicholascc305772017-10-13 16:17:45 -0400136 default:
John Stiles54e7c052021-01-11 14:22:36 -0500137 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400138 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500139 return fContext.fTypes.fFloat->name();
140 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500141 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500142 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500143 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400144 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500145 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400146 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400147 }
148}
149
Brian Osman02bc5222021-01-28 11:00:20 -0500150void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
151 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500152 this->writeLine("struct " + type.name() + " {");
153 fIndentation++;
154 this->writeFields(type.fields(), type.fOffset);
155 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500156 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500157}
158
John Stilesb4418502021-02-04 10:57:08 -0500159void MetalCodeGenerator::writeType(const Type& type) {
160 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500161}
162
Ethan Nicholascc305772017-10-13 16:17:45 -0400163void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 switch (expr.kind()) {
165 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400166 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400167 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400168 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400169 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400170 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400171 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400172 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400173 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400174 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400175 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400176 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400177 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400178 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400179 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400180 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400181 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400182 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400183 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400184 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400185 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400186 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400187 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400189 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400190 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400192 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400193 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400196 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400199 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400200 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400201 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400202 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400203 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400204 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400205 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400206 break;
207 default:
John Stileseada7bc2021-02-02 16:29:32 -0500208 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500209 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400210 }
211}
212
John Stiles06b84ef2020-12-09 12:35:48 -0500213String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
214 const ExpressionArray& arguments,
215 const SkTArray<VariableReference*>& outVars) {
216 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
217 const FunctionDeclaration& function = call.function();
218
219 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) + "_" + function.name();
220 const char* separator = "";
221
222 // Emit a prototype for the function we'll be calling through to in our helper.
223 if (!function.isBuiltin()) {
224 this->writeFunctionDeclaration(function);
225 this->writeLine(";");
226 }
227
228 // Synthesize a helper function that takes the same inputs as `function`, except in places where
229 // `outVars` is non-null; in those places, we take the type of the VariableReference.
230 //
231 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500232 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500233 this->write(" ");
234 this->write(name);
235 this->write("(");
236 this->writeFunctionRequirementParams(function, separator);
237
238 SkASSERT(outVars.size() == arguments.size());
239 SkASSERT(outVars.size() == function.parameters().size());
240
John Stiles73e2c892021-02-13 13:58:01 -0500241 // We need to detect cases where the caller passes the same variable as an out-param more than
242 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
243 // redundant input parameter entirely, and not give it any name.)
244 std::unordered_set<const Variable*> writtenVars;
245
John Stiles06b84ef2020-12-09 12:35:48 -0500246 for (int index = 0; index < arguments.count(); ++index) {
247 this->write(separator);
248 separator = ", ";
249
250 const Variable* param = function.parameters()[index];
251 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
252
253 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500254 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500255
256 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
257 this->write("&");
258 }
259 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500260 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
261 if (didInsert) {
262 this->write(" ");
263 fIgnoreVariableReferenceModifiers = true;
264 this->writeVariableReference(*outVars[index]);
265 fIgnoreVariableReferenceModifiers = false;
266 }
John Stiles06b84ef2020-12-09 12:35:48 -0500267 } else {
268 this->write(" _var");
269 this->write(to_string(index));
270 }
John Stiles06b84ef2020-12-09 12:35:48 -0500271 }
272 this->writeLine(") {");
273
274 ++fIndentation;
275 for (int index = 0; index < outVars.count(); ++index) {
276 if (!outVars[index]) {
277 continue;
278 }
279 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500280 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500281 this->write(" _var");
282 this->write(to_string(index));
283
284 const Variable* param = function.parameters()[index];
285 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
286 this->write(" = ");
287 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500288 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500289 fIgnoreVariableReferenceModifiers = false;
290 }
291
292 this->writeLine(";");
293 }
294
John Stilesf7410bd2021-01-19 13:07:55 -0500295 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500296 bool hasResult = (call.type().name() != "void");
297 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500298 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500299 this->write(" _skResult = ");
300 }
301
302 this->writeName(function.name());
303 this->write("(");
304 separator = "";
305 this->writeFunctionRequirementArgs(function, separator);
306
307 for (int index = 0; index < arguments.count(); ++index) {
308 this->write(separator);
309 separator = ", ";
310
311 this->write("_var");
312 this->write(to_string(index));
313 }
314 this->writeLine(");");
315
316 for (int index = 0; index < outVars.count(); ++index) {
317 if (!outVars[index]) {
318 continue;
319 }
320 // outParam.zyx = _var2;
321 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500322 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500323 fIgnoreVariableReferenceModifiers = false;
324 this->write(" = _var");
325 this->write(to_string(index));
326 this->writeLine(";");
327 }
328
329 if (hasResult) {
330 this->writeLine("return _skResult;");
331 }
332
333 --fIndentation;
334 this->writeLine("}");
335
336 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500337}
338
John Stilesf64e4072020-12-10 10:34:27 -0500339String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
340 return "as_type<" + outType.displayName() + ">";
341}
342
Ethan Nicholascc305772017-10-13 16:17:45 -0400343void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400344 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500345 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
346 // special handling.
347 if (function.isBuiltin() && !function.definition()) {
348 auto iter = fIntrinsicMap.find(function.name());
349 if (iter != fIntrinsicMap.end()) {
350 this->writeIntrinsicCall(c, iter->second);
351 return;
352 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400353 }
John Stilesb21fac22020-12-04 15:36:49 -0500354
John Stilesd7199b22020-12-30 16:22:58 -0500355 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
356 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
357 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
358 // allow a swizzle to be passed to a `floatN&`.)
359 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500360 const std::vector<const Variable*>& parameters = function.parameters();
361 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500362
363 bool foundOutParam = false;
364 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500365 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500366
367 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500368 // If this is an out parameter...
369 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500370 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500371 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500372 // Assignability was verified at IRGeneration time, so this should always succeed.
373 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
374 outVars[index] = info.fAssignedVar;
375 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500376 }
377 }
378
John Stiles06b84ef2020-12-09 12:35:48 -0500379 if (foundOutParam) {
380 // Out parameters need to be written back to at the end of the function. To do this, we
381 // synthesize a helper function which evaluates the out-param expression into a temporary
382 // variable, calls the original function, then writes the temp var back into the out param
383 // using the original out-param expression. (This lets us support things like swizzles and
384 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500385 this->write(getOutParamHelper(c, arguments, outVars));
386 } else {
387 this->write(function.name());
John Stiles06b84ef2020-12-09 12:35:48 -0500388 }
389
Ethan Nicholascc305772017-10-13 16:17:45 -0400390 this->write("(");
391 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500392 this->writeFunctionRequirementArgs(function, separator);
393 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400394 this->write(separator);
395 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500396
397 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500398 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500399 } else {
Brian Osman00185012021-02-04 16:07:11 -0500400 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500401 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400402 }
403 this->write(")");
404}
405
Brian Osman964f0a02020-12-29 10:15:22 -0500406static constexpr char kInverse2x2[] = R"(
407float2x2 float2x2_inverse(float2x2 m) {
408 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
409}
410)";
411
412static constexpr char kInverse3x3[] = R"(
413float3x3 float3x3_inverse(float3x3 m) {
414 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
415 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
416 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
417 float b01 = a22*a11 - a12*a21;
418 float b11 = -a22*a10 + a12*a20;
419 float b21 = a21*a10 - a11*a20;
420 float det = a00*b01 + a01*b11 + a02*b21;
421 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
422 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
423 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
424}
425)";
426
427static constexpr char kInverse4x4[] = R"(
428float4x4 float4x4_inverse(float4x4 m) {
429 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
430 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
431 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
432 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
433 float b00 = a00*a11 - a01*a10;
434 float b01 = a00*a12 - a02*a10;
435 float b02 = a00*a13 - a03*a10;
436 float b03 = a01*a12 - a02*a11;
437 float b04 = a01*a13 - a03*a11;
438 float b05 = a02*a13 - a03*a12;
439 float b06 = a20*a31 - a21*a30;
440 float b07 = a20*a32 - a22*a30;
441 float b08 = a20*a33 - a23*a30;
442 float b09 = a21*a32 - a22*a31;
443 float b10 = a21*a33 - a23*a31;
444 float b11 = a22*a33 - a23*a32;
445 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
446 return float4x4(a11*b11 - a12*b10 + a13*b09,
447 a02*b10 - a01*b11 - a03*b09,
448 a31*b05 - a32*b04 + a33*b03,
449 a22*b04 - a21*b05 - a23*b03,
450 a12*b08 - a10*b11 - a13*b07,
451 a00*b11 - a02*b08 + a03*b07,
452 a32*b02 - a30*b05 - a33*b01,
453 a20*b05 - a22*b02 + a23*b01,
454 a10*b10 - a11*b08 + a13*b06,
455 a01*b08 - a00*b10 - a03*b06,
456 a30*b04 - a31*b02 + a33*b00,
457 a21*b02 - a20*b04 - a23*b00,
458 a11*b07 - a10*b09 - a12*b06,
459 a00*b09 - a01*b07 + a02*b06,
460 a31*b01 - a30*b03 - a32*b00,
461 a20*b03 - a21*b01 + a22*b00) * (1/det);
462}
463)";
464
John Stilesd7199b22020-12-30 16:22:58 -0500465String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
466 // Only use polyfills for a function taking a single-argument square matrix.
467 if (arguments.size() == 1) {
468 const Type& type = arguments.front()->type();
469 if (type.isMatrix() && type.rows() == type.columns()) {
470 // Inject the correct polyfill based on the matrix size.
471 String name = this->typeName(type) + "_inverse";
472 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
473 if (didInsert) {
474 switch (type.rows()) {
475 case 2:
476 fExtraFunctions.writeText(kInverse2x2);
477 break;
478 case 3:
479 fExtraFunctions.writeText(kInverse3x3);
480 break;
481 case 4:
482 fExtraFunctions.writeText(kInverse4x4);
483 break;
484 }
485 }
486 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500487 }
488 }
John Stilesd7199b22020-12-30 16:22:58 -0500489 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
490 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500491}
492
Brian Osman93aed9a2020-12-28 15:18:46 -0500493static constexpr char kMatrixCompMult[] = R"(
494template <int C, int R>
495matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
496 matrix<float, C, R> result;
497 for (int c = 0; c < C; ++c) {
498 result[c] = a[c] * b[c];
499 }
500 return result;
501}
502)";
503
504void MetalCodeGenerator::writeMatrixCompMult() {
505 String name = "matrixCompMult";
506 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
507 fWrittenIntrinsics.insert(name);
508 fExtraFunctions.writeText(kMatrixCompMult);
509 }
510}
511
John Stiles86424eb2020-12-11 11:17:14 -0500512String MetalCodeGenerator::getTempVariable(const Type& type) {
513 String tempVar = "_skTemp" + to_string(fVarCount++);
514 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
515 return tempVar;
516}
517
John Stiles791c27d2020-12-30 14:56:57 -0500518void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
519 // Write out an intrinsic function call exactly as-is. No muss no fuss.
520 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500521 this->writeArgumentList(c.arguments());
522}
523
524void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500525 this->write("(");
526 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500527 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500528 this->write(separator);
529 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500530 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500531 }
532 this->write(")");
533}
534
John Stilesd7199b22020-12-30 16:22:58 -0500535void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400536 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400537 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500538 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500539 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400540 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500541 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400542 this->write(SAMPLER_SUFFIX);
543 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400544 const Type& arg1Type = arguments[1]->type();
John Stiles54e7c052021-01-11 14:22:36 -0500545 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500546 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500547 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500548 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500549 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500550 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400551 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500552 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Brian Osman00185012021-02-04 16:07:11 -0500553 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400554 this->write(")");
555 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400556 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400557 }
John Stilesd7199b22020-12-30 16:22:58 -0500558 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400559 // 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 -0500560 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500561 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500562 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500563 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500564 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500565 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500566 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400567 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500568 }
Brian Osman46787d52020-11-24 14:18:23 -0500569 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500570 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500571 if (arguments[0]->type().columns() == 1) {
572 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500573 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500574 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500575 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500576 this->write(")");
577 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500578 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500579 }
580 break;
581 }
John Stilesd7199b22020-12-30 16:22:58 -0500582 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500583 if (arguments[0]->type().columns() == 1) {
584 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500585 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500586 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500587 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500588 this->write(")");
589 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500590 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500591 }
592 break;
593 }
John Stilesd7199b22020-12-30 16:22:58 -0500594 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500595 if (arguments[0]->type().columns() == 1) {
596 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
597 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500598 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500599 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500600 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500601 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500602 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500603 this->write("))");
604 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500605 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500606 }
607 break;
608 }
John Stilesd7199b22020-12-30 16:22:58 -0500609 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500610 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500611 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500612 this->write(")");
613 break;
614 }
John Stilesd7199b22020-12-30 16:22:58 -0500615 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500616 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500617 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500618 this->write(")");
619 break;
620 }
John Stilesd7199b22020-12-30 16:22:58 -0500621 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500622 this->write(this->getBitcastIntrinsic(c.type()));
623 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500624 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500625 this->write(")");
626 break;
627 }
John Stilesd7199b22020-12-30 16:22:58 -0500628 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500629 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500630 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500631 this->write(") * 57.2957795)");
632 break;
633 }
John Stilesd7199b22020-12-30 16:22:58 -0500634 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500635 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500636 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500637 this->write(") * 0.0174532925)");
638 break;
639 }
John Stilesd7199b22020-12-30 16:22:58 -0500640 case kDFdx_IntrinsicKind: {
641 this->write("dfdx");
642 this->writeArgumentList(c.arguments());
643 break;
644 }
645 case kDFdy_IntrinsicKind: {
646 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500647 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500648 this->write("-");
649 }
650 this->write("dfdy");
651 this->writeArgumentList(c.arguments());
652 break;
653 }
654 case kInverse_IntrinsicKind: {
655 this->write(this->getInversePolyfill(arguments));
656 this->writeArgumentList(c.arguments());
657 break;
658 }
659 case kInversesqrt_IntrinsicKind: {
660 this->write("rsqrt");
661 this->writeArgumentList(c.arguments());
662 break;
663 }
664 case kAtan_IntrinsicKind: {
665 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
666 this->writeArgumentList(c.arguments());
667 break;
668 }
669 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500670 if (arguments[0]->type().columns() == 1) {
671 // We need to synthesize `I - 2 * N * I * N`.
672 String tmpI = this->getTempVariable(arguments[0]->type());
673 String tmpN = this->getTempVariable(arguments[1]->type());
674
675 // (_skTempI = ...
676 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500677 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500678
679 // , _skTempN = ...
680 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500681 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500682
683 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
684 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
685 } else {
686 this->writeSimpleIntrinsic(c);
687 }
688 break;
689 }
John Stilesd7199b22020-12-30 16:22:58 -0500690 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500691 if (arguments[0]->type().columns() == 1) {
692 // Metal does implement refract for vectors; rather than reimplementing refract from
693 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
694 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500695 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500696 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500697 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500698 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500699 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500700 this->write(").x)");
701 } else {
702 this->writeSimpleIntrinsic(c);
703 }
704 break;
705 }
John Stiles23456532020-12-30 18:12:48 -0500706 case kRoundEven_IntrinsicKind: {
707 this->write("rint");
708 this->writeArgumentList(c.arguments());
709 break;
710 }
John Stilesd7199b22020-12-30 16:22:58 -0500711 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500712 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500713 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500714 this->write(")");
715 break;
716 }
John Stilesd7199b22020-12-30 16:22:58 -0500717 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500718 // Create a temp variable to store the expression, to avoid double-evaluating it.
719 String skTemp = this->getTempVariable(arguments[0]->type());
720 String exprType = this->typeName(arguments[0]->type());
721
722 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
723 // Use select to detect zero inputs and force a -1 result.
724
725 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
726 this->write("(");
727 this->write(skTemp);
728 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500729 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500730 this->write("), select(ctz(");
731 this->write(skTemp);
732 this->write("), ");
733 this->write(exprType);
734 this->write("(-1), ");
735 this->write(skTemp);
736 this->write(" == ");
737 this->write(exprType);
738 this->write("(0)))");
739 break;
740 }
John Stilesd7199b22020-12-30 16:22:58 -0500741 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500742 // Create a temp variable to store the expression, to avoid double-evaluating it.
743 String skTemp1 = this->getTempVariable(arguments[0]->type());
744 String exprType = this->typeName(arguments[0]->type());
745
746 // GLSL findMSB is actually quite different from Metal's clz:
747 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
748 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
749
750 // (_skTemp1 = (.....),
751 this->write("(");
752 this->write(skTemp1);
753 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500754 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500755 this->write("), ");
756
757 // Signed input types might be negative; we need another helper variable to negate the
758 // input (since we can only find one bits, not zero bits).
759 String skTemp2;
760 if (arguments[0]->type().isSigned()) {
761 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
762 skTemp2 = this->getTempVariable(arguments[0]->type());
763 this->write(skTemp2);
764 this->write(" = (select(");
765 this->write(skTemp1);
766 this->write(", ~");
767 this->write(skTemp1);
768 this->write(", ");
769 this->write(skTemp1);
770 this->write(" < 0)), ");
771 } else {
772 skTemp2 = skTemp1;
773 }
774
775 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
776 this->write("select(");
777 this->write(this->typeName(c.type()));
778 this->write("(clz(");
779 this->write(skTemp2);
780 this->write(")), ");
781 this->write(this->typeName(c.type()));
782 this->write("(-1), ");
783 this->write(skTemp2);
784 this->write(" == ");
785 this->write(exprType);
786 this->write("(0)))");
787 break;
788 }
John Stilesd7199b22020-12-30 16:22:58 -0500789 case kMatrixCompMult_IntrinsicKind: {
790 this->writeMatrixCompMult();
791 this->writeSimpleIntrinsic(c);
792 break;
793 }
794 case kCompareEqual_IntrinsicKind:
795 case kCompareGreaterThan_IntrinsicKind:
796 case kCompareGreaterThanEqual_IntrinsicKind:
797 case kCompareLessThan_IntrinsicKind:
798 case kCompareLessThanEqual_IntrinsicKind:
799 case kCompareNotEqual_IntrinsicKind: {
800 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500801 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500802 switch (kind) {
803 case kCompareEqual_IntrinsicKind:
804 this->write(" == ");
805 break;
806 case kCompareNotEqual_IntrinsicKind:
807 this->write(" != ");
808 break;
809 case kCompareLessThan_IntrinsicKind:
810 this->write(" < ");
811 break;
812 case kCompareLessThanEqual_IntrinsicKind:
813 this->write(" <= ");
814 break;
815 case kCompareGreaterThan_IntrinsicKind:
816 this->write(" > ");
817 break;
818 case kCompareGreaterThanEqual_IntrinsicKind:
819 this->write(" >= ");
820 break;
821 default:
John Stilesf57207b2021-02-02 17:50:34 -0500822 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500823 }
Brian Osman00185012021-02-04 16:07:11 -0500824 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500825 this->write(")");
826 break;
827 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400828 default:
John Stilesf57207b2021-02-02 17:50:34 -0500829 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400830 }
831}
832
John Stilesfcf8cb22020-08-06 14:29:22 -0400833// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
834// Cells that don't exist in the source matrix will be populated with identity-matrix values.
835void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
836 SkASSERT(rows <= 4);
837 SkASSERT(columns <= 4);
838
839 const char* columnSeparator = "";
840 for (int c = 0; c < columns; ++c) {
841 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
842 columnSeparator = "), ";
843
844 // Determine how many values to take from the source matrix for this row.
845 int swizzleLength = 0;
846 if (c < sourceMatrix.columns()) {
847 swizzleLength = std::min<>(rows, sourceMatrix.rows());
848 }
849
850 // Emit all the values from the source matrix row.
851 bool firstItem;
852 switch (swizzleLength) {
853 case 0: firstItem = true; break;
854 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
855 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
856 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
857 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
858 default: SkUNREACHABLE;
859 }
860
861 // Emit the placeholder identity-matrix cells.
862 for (int r = swizzleLength; r < rows; ++r) {
863 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
864 firstItem = false;
865 }
866 }
867
868 fExtraFunctions.writeText(")");
869}
870
871// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
872// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400873void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
874 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400875 size_t argIndex = 0;
876 int argPosition = 0;
877
878 const char* columnSeparator = "";
879 for (int c = 0; c < columns; ++c) {
880 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
881 columnSeparator = "), ";
882
883 const char* rowSeparator = "";
884 for (int r = 0; r < rows; ++r) {
885 fExtraFunctions.writeText(rowSeparator);
886 rowSeparator = ", ";
887
888 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400889 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400890 switch (argType.typeKind()) {
891 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400892 fExtraFunctions.printf("x%zu", argIndex);
893 break;
894 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400895 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400896 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
897 break;
898 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400899 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400900 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
901 argPosition / argType.rows(),
902 argPosition % argType.rows());
903 break;
904 }
905 default: {
906 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
907 fExtraFunctions.writeText("<error>");
908 break;
909 }
910 }
911
912 ++argPosition;
913 if (argPosition >= argType.columns() * argType.rows()) {
914 ++argIndex;
915 argPosition = 0;
916 }
917 } else {
918 SkDEBUGFAIL("not enough arguments for matrix constructor");
919 fExtraFunctions.writeText("<error>");
920 }
921 }
922 }
923
924 if (argPosition != 0 || argIndex != args.size()) {
925 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
926 fExtraFunctions.writeText(", <error>");
927 }
928
929 fExtraFunctions.writeText(")");
930}
931
John Stiles1bdafbf2020-05-28 12:17:20 -0400932// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
933// Keeps track of previously generated constructors so that we won't generate more than one
934// constructor for any given permutation of input argument types. Returns the name of the
935// generated constructor method.
936String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400937 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500938 int columns = matrix.columns();
939 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400940 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400941
942 // Create the helper-method name and use it as our lookup key.
943 String name;
944 name.appendf("float%dx%d_from", columns, rows);
945 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500946 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400947 }
948
949 // If a helper-method has already been synthesized, we don't need to synthesize it again.
950 auto [iter, newlyCreated] = fHelpers.insert(name);
951 if (!newlyCreated) {
952 return name;
953 }
954
955 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
956 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
957 // supply a mixture of scalars and vectors.)
958 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
959
960 size_t argIndex = 0;
961 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400962 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400963 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500964 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400965 argSeparator = ", ";
966 }
967
968 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
969
John Stiles9aeed132020-11-24 17:36:06 -0500970 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400971 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400972 } else {
973 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400974 }
975
John Stilesfcf8cb22020-08-06 14:29:22 -0400976 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500977 return name;
978}
979
980bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
981 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
982 return false;
983 }
984 if (t1.columns() > 1) {
985 return this->canCoerce(t1.componentType(), t2.componentType());
986 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500987 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500988}
989
John Stiles1bdafbf2020-05-28 12:17:20 -0400990bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
991 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500992 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400993 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500994 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400995
996 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
997 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
998 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
999 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1000 // that converts our inputs into a properly-shaped matrix.
1001 // A matrix construct helper method is always used if any input argument is a matrix.
1002 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1003 //
1004 // float2 x = (1, 2);
1005 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1006 // | 2 4 6 |
1007 //
1008 // float2 x = (2, 3);
1009 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1010 // | 2 4 6 |
1011 //
1012 // float4 x = (1, 2, 3, 4);
1013 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1014 // | 2 4 |
1015 //
1016
1017 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001018 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001019 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001020 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001021 return true;
1022 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001023 position += expr->type().columns();
1024 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001025 // An input argument would span multiple rows; a helper function is required.
1026 return true;
1027 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001028 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001029 // We've advanced to the end of a row. Wrap to the start of the next row.
1030 position = 0;
1031 }
1032 }
1033
1034 return false;
1035}
1036
1037void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001038 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001039 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001040 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001041 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001042 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001043 const Type& argType = arg.type();
1044 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001045 this->writeExpression(arg, parentPrecedence);
1046 return;
1047 }
1048
1049 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
1050 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -05001051 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001052 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -04001053 this->write("float");
1054 this->write(to_string(matrix.columns()));
1055 this->write("x");
1056 this->write(to_string(matrix.rows()));
1057 this->write("(");
1058 this->writeExpression(arg, parentPrecedence);
1059 this->write(")");
1060 return;
1061 }
1062 }
1063
1064 // Emit and invoke a matrix-constructor helper method if one is necessary.
1065 if (this->matrixConstructHelperIsNeeded(c)) {
1066 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001067 this->write("(");
1068 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001069 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001070 this->write(separator);
1071 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001072 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001073 }
John Stiles1fa15b12020-05-28 17:36:54 +00001074 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001075 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001076 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001077
1078 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stilesb4418502021-02-04 10:57:08 -05001079 this->writeType(constructorType);
1080 this->write(constructorType.isArray() ? "{" : "(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001081 const char* separator = "";
1082 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001083 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001084 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001085 this->write(separator);
1086 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001087 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001088 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001089 // Merge scalars and smaller vectors together.
1090 if (!scalarCount) {
John Stilesb4418502021-02-04 10:57:08 -05001091 this->writeType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001092 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001093 this->write("(");
1094 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001095 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001096 }
Brian Osman00185012021-02-04 16:07:11 -05001097 this->writeExpression(*arg, Precedence::kSequence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001098 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001099 this->write(")");
1100 scalarCount = 0;
1101 }
1102 }
John Stilesb4418502021-02-04 10:57:08 -05001103 this->write(constructorType.isArray() ? "}" : ")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001104}
1105
1106void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001107 if (fRTHeightName.length()) {
1108 this->write("float4(_fragCoord.x, ");
1109 this->write(fRTHeightName.c_str());
1110 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001111 } else {
1112 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1113 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001114}
1115
1116void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001117 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001118 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001119 // we're actually targeting the clones.
1120 if (fIgnoreVariableReferenceModifiers) {
1121 this->writeName(ref.variable()->name());
1122 return;
1123 }
1124
Ethan Nicholas78686922020-10-08 06:46:27 -04001125 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001126 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001127 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001128 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001129 case SK_FRAGCOORD_BUILTIN:
1130 this->writeFragCoord();
1131 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001132 case SK_VERTEXID_BUILTIN:
1133 this->write("sk_VertexID");
1134 break;
1135 case SK_INSTANCEID_BUILTIN:
1136 this->write("sk_InstanceID");
1137 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001138 case SK_CLOCKWISE_BUILTIN:
1139 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001140 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001141 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001142 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001143 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001144 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001145 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001146 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001147 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001148 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001149 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001150 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1151 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001152 this->write("_uniforms.");
1153 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001154 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001155 }
1156 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001157 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001158 }
1159}
1160
1161void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001162 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001163 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001164 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001165 this->write("]");
1166}
1167
1168void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001169 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1170 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001171 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001172 this->write(".");
1173 }
Timothy Liang7d637782018-06-05 09:58:07 -04001174 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001175 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001176 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001177 break;
1178 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001179 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001180 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001181 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001182 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001183 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001184 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1185 this->write("->");
1186 }
Timothy Liang651286f2018-06-07 09:55:33 -04001187 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001188 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001189 }
1190}
1191
1192void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001193 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001194 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001195 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001196 SkASSERT(c >= 0 && c <= 3);
1197 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001198 }
1199}
1200
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001201void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1202 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001203 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001204
1205 auto [iter, wasInserted] = fHelpers.insert(key);
1206 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001207 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001208 " left = left * right;\n"
1209 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001210 "}\n",
1211 this->typeName(result).c_str(), this->typeName(left).c_str(),
1212 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001213 }
1214}
1215
John Stiles01cdf012021-02-10 09:53:41 -05001216void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1217 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1218 left.description().c_str(), right.description().c_str());
1219
1220 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1221
1222 auto [iter, wasInserted] = fHelpers.insert(key);
1223 if (wasInserted) {
1224 fExtraFunctions.printf(
1225 "thread bool operator==(const %s left, const %s right) {\n"
1226 " return",
1227 this->typeName(left).c_str(), this->typeName(right).c_str());
1228
1229 for (int index=0; index<left.columns(); ++index) {
1230 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1231 index == 0 ? "" : " &&", index, index);
1232 }
1233 fExtraFunctions.printf(";\n"
1234 "}\n");
1235 }
1236}
1237
1238void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1239 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1240 left.description().c_str(), right.description().c_str());
1241
1242 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1243
1244 auto [iter, wasInserted] = fHelpers.insert(key);
1245 if (wasInserted) {
1246 fExtraFunctions.printf(
1247 "thread bool operator!=(const %s left, const %s right) {\n"
1248 " return",
1249 this->typeName(left).c_str(), this->typeName(right).c_str());
1250
1251 for (int index=0; index<left.columns(); ++index) {
1252 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1253 index == 0 ? "" : " ||", index, index);
1254 }
1255 fExtraFunctions.printf(";\n"
1256 "}\n");
1257 }
1258}
1259
Ethan Nicholascc305772017-10-13 16:17:45 -04001260void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1261 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001262 const Expression& left = *b.left();
1263 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001264 const Type& leftType = left.type();
1265 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001266 Operator op = b.getOperator();
1267 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001268 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001269 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001270 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001271 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001272 this->write("all");
1273 needParens = true;
1274 }
1275 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001276 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001277 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001278 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001279 needParens = true;
1280 }
1281 break;
1282 default:
1283 break;
1284 }
1285 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001286 this->write("(");
1287 }
John Stiles01cdf012021-02-10 09:53:41 -05001288 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001289 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001290 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001291 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001292 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001293 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001294 this->writeMatrixInequalityHelper(leftType, rightType);
1295 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001296 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001297 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001298 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001299 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001300 // This doesn't compile in Metal:
1301 // float4 x = float4(1);
1302 // x.xy *= float2x2(...);
1303 // with the error message "non-const reference cannot bind to vector element",
1304 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1305 // as long as the LHS has no side effects, and hope for the best otherwise.
1306 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001307 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001308 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001309 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001310 SkASSERT(opName.endsWith("="));
1311 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001312 this->write(" ");
1313 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001314 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001315 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001316 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001317 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001318 this->write(")");
1319 }
1320}
1321
1322void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1323 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001324 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001325 this->write("(");
1326 }
Brian Osman00185012021-02-04 16:07:11 -05001327 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001328 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001329 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001330 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001331 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1332 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001333 this->write(")");
1334 }
1335}
1336
1337void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1338 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001339 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001340 this->write("(");
1341 }
John Stilesd6449e92020-11-30 09:13:23 -05001342 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001343 this->writeExpression(*p.operand(), Precedence::kPrefix);
1344 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001345 this->write(")");
1346 }
1347}
1348
1349void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1350 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001351 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001352 this->write("(");
1353 }
Brian Osman00185012021-02-04 16:07:11 -05001354 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001355 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001356 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001357 this->write(")");
1358 }
1359}
1360
1361void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001362 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001363}
1364
1365void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001366 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001367 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001368 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001369 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001370 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001371 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001372 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001373 } else {
John Stiles12739df2020-12-29 09:47:20 -05001374 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001375 }
1376}
1377
1378void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001379 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001380}
1381
1382void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001383 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001384}
1385
John Stiles06b84ef2020-12-09 12:35:48 -05001386void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1387 const char*& separator) {
1388 Requirements requirements = this->requirements(f);
1389 if (requirements & kInputs_Requirement) {
1390 this->write(separator);
1391 this->write("_in");
1392 separator = ", ";
1393 }
1394 if (requirements & kOutputs_Requirement) {
1395 this->write(separator);
1396 this->write("_out");
1397 separator = ", ";
1398 }
1399 if (requirements & kUniforms_Requirement) {
1400 this->write(separator);
1401 this->write("_uniforms");
1402 separator = ", ";
1403 }
1404 if (requirements & kGlobals_Requirement) {
1405 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001406 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001407 separator = ", ";
1408 }
1409 if (requirements & kFragCoord_Requirement) {
1410 this->write(separator);
1411 this->write("_fragCoord");
1412 separator = ", ";
1413 }
1414}
1415
1416void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1417 const char*& separator) {
1418 Requirements requirements = this->requirements(f);
1419 if (requirements & kInputs_Requirement) {
1420 this->write(separator);
1421 this->write("Inputs _in");
1422 separator = ", ";
1423 }
1424 if (requirements & kOutputs_Requirement) {
1425 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001426 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001427 separator = ", ";
1428 }
1429 if (requirements & kUniforms_Requirement) {
1430 this->write(separator);
1431 this->write("Uniforms _uniforms");
1432 separator = ", ";
1433 }
1434 if (requirements & kGlobals_Requirement) {
1435 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001436 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001437 separator = ", ";
1438 }
1439 if (requirements & kFragCoord_Requirement) {
1440 this->write(separator);
1441 this->write("float4 _fragCoord");
1442 separator = ", ";
1443 }
1444}
1445
John Stilesda5cdf62021-01-28 11:47:29 -05001446int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1447 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001448 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001449}
1450
1451int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1452 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001453 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001454}
1455
John Stiles569249b2020-11-03 12:18:22 -05001456bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001457 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001458 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001459 if ("main" == f.name()) {
John Stiles270cec22021-02-17 12:59:36 -05001460 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001461 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001462 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001463 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001464 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001465 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001466 break;
1467 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001468 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001469 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001470 }
1471 this->write("(Inputs _in [[stage_in]]");
1472 if (-1 != fUniformBuffer) {
1473 this->write(", constant Uniforms& _uniforms [[buffer(" +
1474 to_string(fUniformBuffer) + ")]]");
1475 }
Brian Osman133724c2020-10-28 14:14:39 -04001476 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001477 if (e->is<GlobalVarDeclaration>()) {
1478 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001479 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1480 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1481 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001482 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001483 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001484 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001485 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001486 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001487 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001488 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001489 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001490 }
1491 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001492 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001493 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001494 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001495 this->write(")]]");
1496 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001497 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001498 this->write(SAMPLER_SUFFIX);
1499 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001500 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001501 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001502 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001503 } else if (e->is<InterfaceBlock>()) {
1504 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001505 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001506 continue;
1507 }
1508 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001509 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001510 this->write("& " );
1511 this->write(fInterfaceBlockNameMap[&intf]);
1512 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001513 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001514 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001515 }
1516 }
John Stiles270cec22021-02-17 12:59:36 -05001517 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001518 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001519 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001520 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001521 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001522 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001523 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001524 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001525 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001526 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001527 separator = ", ";
1528 } else {
John Stilesb4418502021-02-04 10:57:08 -05001529 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001530 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001531 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001532 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001533 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001534 }
John Stiles569249b2020-11-03 12:18:22 -05001535 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001536 this->write(separator);
1537 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001538 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001539 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001540 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001541 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001542 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001543 }
Timothy Liang651286f2018-06-07 09:55:33 -04001544 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001545 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001546 }
John Stiles569249b2020-11-03 12:18:22 -05001547 this->write(")");
1548 return true;
1549}
Ethan Nicholascc305772017-10-13 16:17:45 -04001550
John Stiles569249b2020-11-03 12:18:22 -05001551void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1552 this->writeFunctionDeclaration(f.declaration());
1553 this->writeLine(";");
1554}
1555
John Stiles986c7fb2020-12-01 14:44:56 -05001556static bool is_block_ending_with_return(const Statement* stmt) {
1557 // This function detects (potentially nested) blocks that end in a return statement.
1558 if (!stmt->is<Block>()) {
1559 return false;
1560 }
1561 const StatementArray& block = stmt->as<Block>().children();
1562 for (int index = block.count(); index--; ) {
1563 const Statement& stmt = *block[index];
1564 if (stmt.is<ReturnStatement>()) {
1565 return true;
1566 }
1567 if (stmt.is<Block>()) {
1568 return is_block_ending_with_return(&stmt);
1569 }
1570 if (!stmt.is<Nop>()) {
1571 break;
1572 }
1573 }
1574 return false;
1575}
1576
John Stiles569249b2020-11-03 12:18:22 -05001577void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001578 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001579
John Stiles569249b2020-11-03 12:18:22 -05001580 if (!this->writeFunctionDeclaration(f.declaration())) {
1581 return;
1582 }
1583
John Stiles986c7fb2020-12-01 14:44:56 -05001584 fCurrentFunction = &f.declaration();
1585 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1586
John Stiles569249b2020-11-03 12:18:22 -05001587 this->writeLine(" {");
1588
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001589 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001590 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001591 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001592 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001593 }
John Stilesc67b3622020-05-28 17:53:13 -04001594
Ethan Nicholascc305772017-10-13 16:17:45 -04001595 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001596 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001597 {
1598 AutoOutputStream outputToBuffer(this, &buffer);
1599 fIndentation++;
1600 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1601 if (!stmt->isEmpty()) {
1602 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001603 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001604 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001605 }
John Stiles44532372020-12-07 12:33:55 -05001606 if (f.declaration().name() == "main") {
1607 // If the main function doesn't end with a return, we need to synthesize one here.
1608 if (!is_block_ending_with_return(f.body().get())) {
1609 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001610 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001611 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001612 }
John Stiles44532372020-12-07 12:33:55 -05001613 fIndentation--;
1614 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001615 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001616 this->write(fFunctionHeader);
1617 this->write(buffer.str());
1618}
1619
1620void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001621 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001622 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1623 this->write("thread ");
1624 }
1625 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001626 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001627 }
1628}
1629
1630void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001631 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001632 return;
1633 }
John Stiles06b84ef2020-12-09 12:35:48 -05001634 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001635 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001636 this->writeLine(intf.typeName() + " {");
1637 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001638 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001639 structType = &structType->componentType();
1640 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001641 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001642 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001643 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001644 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001645 }
1646 fIndentation--;
1647 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001648 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001649 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001650 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001651 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001652 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001653 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001654 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001655 } else if (intf.arraySize() == Type::kUnsizedArray){
1656 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001657 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001658 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001659 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001660 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001661 }
1662 this->writeLine(";");
1663}
1664
Timothy Liangdc89f192018-06-13 09:20:31 -04001665void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1666 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001667 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001668 int currentOffset = 0;
1669 for (const auto& field: fields) {
1670 int fieldOffset = field.fModifiers.fLayout.fOffset;
1671 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001672 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001673 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1674 return;
1675 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001676 if (fieldOffset != -1) {
1677 if (currentOffset > fieldOffset) {
1678 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001679 "offset of field '" + field.fName + "' must be at least " +
1680 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001681 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001682 } else if (currentOffset < fieldOffset) {
1683 this->write("char pad");
1684 this->write(to_string(fPaddingCount++));
1685 this->write("[");
1686 this->write(to_string(fieldOffset - currentOffset));
1687 this->writeLine("];");
1688 currentOffset = fieldOffset;
1689 }
1690 int alignment = memoryLayout.alignment(*fieldType);
1691 if (fieldOffset % alignment) {
1692 fErrors.error(parentOffset,
1693 "offset of field '" + field.fName + "' must be a multiple of " +
1694 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001695 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001696 }
1697 }
Brian Osman8609a242020-09-08 14:01:49 -04001698 size_t fieldSize = memoryLayout.size(*fieldType);
1699 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1700 fErrors.error(parentOffset, "field offset overflow");
1701 return;
1702 }
1703 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001704 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001705 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001706 this->write(" ");
1707 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001708 this->writeLine(";");
1709 if (parentIntf) {
1710 fInterfaceBlockMap[&field] = parentIntf;
1711 }
1712 }
1713}
1714
Ethan Nicholascc305772017-10-13 16:17:45 -04001715void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001716 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001717}
1718
Timothy Liang651286f2018-06-07 09:55:33 -04001719void MetalCodeGenerator::writeName(const String& name) {
1720 if (fReservedWords.find(name) != fReservedWords.end()) {
1721 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1722 }
1723 this->write(name);
1724}
1725
John Stilesb4418502021-02-04 10:57:08 -05001726void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1727 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001728 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001729 }
John Stilesb4418502021-02-04 10:57:08 -05001730 this->writeModifiers(varDecl.var().modifiers(), global);
1731 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001732 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001733 this->writeName(varDecl.var().name());
1734 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001735 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001736 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001737 }
1738 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001739}
1740
1741void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001742 switch (s.kind()) {
1743 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001744 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001745 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001746 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001747 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001748 this->write(";");
1749 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001750 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001751 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001752 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001753 case Statement::Kind::kVarDeclaration:
1754 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001755 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001756 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001757 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001758 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001759 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001760 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001762 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001763 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001764 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001765 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001766 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001767 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001768 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001769 this->write("break;");
1770 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001771 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001772 this->write("continue;");
1773 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001774 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001775 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001776 break;
John Stiles98c1f822020-09-09 14:18:53 -04001777 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001778 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001779 this->write(";");
1780 break;
1781 default:
John Stileseada7bc2021-02-02 16:29:32 -05001782 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001783 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001784 }
1785}
1786
Ethan Nicholascc305772017-10-13 16:17:45 -04001787void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001788 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1789 // something here to make the code valid).
1790 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001791 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001792 this->writeLine("{");
1793 fIndentation++;
1794 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001795 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1796 if (!stmt->isEmpty()) {
1797 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001798 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001799 }
1800 }
1801 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001802 fIndentation--;
1803 this->write("}");
1804 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001805}
1806
1807void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1808 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001809 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001810 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001811 this->writeStatement(*stmt.ifTrue());
1812 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001813 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001814 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001815 }
1816}
1817
1818void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001819 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1820 if (!f.initializer() && f.test() && !f.next()) {
1821 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001822 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001823 this->write(") ");
1824 this->writeStatement(*f.statement());
1825 return;
1826 }
1827
Ethan Nicholascc305772017-10-13 16:17:45 -04001828 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001829 if (f.initializer() && !f.initializer()->isEmpty()) {
1830 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001831 } else {
1832 this->write("; ");
1833 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001834 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001835 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001836 }
1837 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001838 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001839 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001840 }
1841 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001842 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001843}
1844
Ethan Nicholascc305772017-10-13 16:17:45 -04001845void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1846 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001847 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001849 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001850 this->write(");");
1851}
1852
1853void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1854 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001855 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001856 this->writeLine(") {");
1857 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001858 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1859 const SwitchCase& c = stmt->as<SwitchCase>();
1860 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001861 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001862 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001863 this->writeLine(":");
1864 } else {
1865 this->writeLine("default:");
1866 }
John Stilesb23a64b2021-03-11 08:27:59 -05001867 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001868 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001869 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001870 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001871 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001872 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001873 }
1874 fIndentation--;
1875 this->write("}");
1876}
1877
John Stiles986c7fb2020-12-01 14:44:56 -05001878void MetalCodeGenerator::writeReturnStatementFromMain() {
1879 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001880 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001881 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001882 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001883 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001884 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001885 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001886 break;
1887 default:
1888 SkDEBUGFAIL("unsupported kind of program");
1889 }
1890}
1891
Ethan Nicholascc305772017-10-13 16:17:45 -04001892void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stiles986c7fb2020-12-01 14:44:56 -05001893 if (fCurrentFunction && fCurrentFunction->name() == "main") {
1894 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001895 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1896 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001897 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001898 this->writeLine(";");
1899 } else {
1900 fErrors.error(r.fOffset, "Metal does not support returning '" +
1901 r.expression()->type().description() + "' from main()");
1902 }
John Stiles986c7fb2020-12-01 14:44:56 -05001903 }
1904 this->writeReturnStatementFromMain();
1905 return;
1906 }
1907
Ethan Nicholascc305772017-10-13 16:17:45 -04001908 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001909 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001910 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001911 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001912 }
1913 this->write(";");
1914}
1915
Michael Ludwigbf58add2021-03-16 10:40:11 -04001916void MetalCodeGenerator::writeHeader() {
1917 this->write("#include <metal_stdlib>\n");
1918 this->write("#include <simd/simd.h>\n");
1919 this->write("using namespace metal;\n");
1920}
1921
Ethan Nicholascc305772017-10-13 16:17:45 -04001922void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001923 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001924 if (e->is<GlobalVarDeclaration>()) {
1925 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001926 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001927 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001928 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001929 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001930 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001931 if (-1 == fUniformBuffer) {
1932 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001933 fUniformBuffer = uniformSet;
1934 } else if (uniformSet != fUniformBuffer) {
1935 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1936 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001937 }
1938 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001939 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001940 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001941 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001942 this->write(";\n");
1943 }
1944 }
1945 }
1946 if (-1 != fUniformBuffer) {
1947 this->write("};\n");
1948 }
1949}
1950
1951void MetalCodeGenerator::writeInputStruct() {
1952 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001953 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001954 if (e->is<GlobalVarDeclaration>()) {
1955 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001956 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001957 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1958 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001959 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001960 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001961 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001962 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001963 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05001964 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04001965 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001966 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05001967 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04001968 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001969 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001970 }
1971 }
1972 this->write(";\n");
1973 }
1974 }
1975 }
1976 this->write("};\n");
1977}
1978
1979void MetalCodeGenerator::writeOutputStruct() {
1980 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05001981 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001982 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05001983 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04001984 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001985 }
Brian Osman133724c2020-10-28 14:14:39 -04001986 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001987 if (e->is<GlobalVarDeclaration>()) {
1988 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001989 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001990 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1991 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001992 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001993 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001994 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001995 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05001996
1997 int location = var.modifiers().fLayout.fLocation;
1998 if (location < 0) {
1999 fErrors.error(var.fOffset,
2000 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002001 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002002 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002003 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002004 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002005 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002006 if (colorIndex) {
2007 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002008 }
Brian Osmanc0213602020-10-06 14:43:32 -04002009 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002010 }
2011 this->write(";\n");
2012 }
2013 }
Timothy Liang7d637782018-06-05 09:58:07 -04002014 }
John Stiles270cec22021-02-17 12:59:36 -05002015 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002016 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002017 }
2018 this->write("};\n");
2019}
2020
2021void MetalCodeGenerator::writeInterfaceBlocks() {
2022 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002023 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002024 if (e->is<InterfaceBlock>()) {
2025 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002026 wroteInterfaceBlock = true;
2027 }
2028 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002029 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002030 this->writeLine("struct sksl_synthetic_uniforms {");
2031 this->writeLine(" float u_skRTHeight;");
2032 this->writeLine("};");
2033 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002034}
2035
John Stilesdc75a972020-11-25 16:24:55 -05002036void MetalCodeGenerator::writeStructDefinitions() {
2037 for (const ProgramElement* e : fProgram.elements()) {
2038 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002039 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002040 }
2041 }
2042}
2043
John Stilescdcdb042020-07-06 09:03:51 -04002044void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2045 // Visit the interface blocks.
2046 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002047 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002048 }
Brian Osman133724c2020-10-28 14:14:39 -04002049 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002050 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002051 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002052 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002053 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2054 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2055 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002056 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002057 var.type().typeKind() == Type::TypeKind::kSampler) {
2058 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2059 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002060 visitor->visitTexture(var.type(), var.name());
2061 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002062 } else {
2063 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002064 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002065 }
2066 }
2067 }
John Stilescdcdb042020-07-06 09:03:51 -04002068}
2069
2070void MetalCodeGenerator::writeGlobalStruct() {
2071 class : public GlobalStructVisitor {
2072 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002073 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002074 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002075 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002076 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002077 fCodeGen->write("* ");
2078 fCodeGen->writeName(blockName);
2079 fCodeGen->write(";\n");
2080 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002081 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002082 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002083 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002084 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002085 fCodeGen->write(" ");
2086 fCodeGen->writeName(name);
2087 fCodeGen->write(";\n");
2088 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002089 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002090 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002091 fCodeGen->write(" sampler ");
2092 fCodeGen->writeName(name);
2093 fCodeGen->write(";\n");
2094 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002095 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002096 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002097 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002098 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002099 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002100 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002101 fCodeGen->write(";\n");
2102 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002103 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002104 if (fFirst) {
2105 fCodeGen->write("struct Globals {\n");
2106 fFirst = false;
2107 }
2108 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002109 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002110 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002111 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002112 fFirst = true;
2113 }
2114 }
2115
2116 MetalCodeGenerator* fCodeGen = nullptr;
2117 bool fFirst = true;
2118 } visitor;
2119
2120 visitor.fCodeGen = this;
2121 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002122 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002123}
2124
2125void MetalCodeGenerator::writeGlobalInit() {
2126 class : public GlobalStructVisitor {
2127 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002128 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002129 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002130 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002131 fCodeGen->write("&");
2132 fCodeGen->writeName(blockName);
2133 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002134 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002135 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002136 fCodeGen->writeName(name);
2137 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002138 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002139 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002140 fCodeGen->writeName(name);
2141 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002142 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002143 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002144 if (value) {
2145 fCodeGen->writeVarInitializer(var, *value);
2146 } else {
2147 fCodeGen->write("{}");
2148 }
2149 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002150 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002151 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002152 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002153 fFirst = false;
2154 } else {
2155 fCodeGen->write(", ");
2156 }
2157 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002158 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002159 if (!fFirst) {
2160 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002161 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002162 }
2163 }
2164 MetalCodeGenerator* fCodeGen = nullptr;
2165 bool fFirst = true;
2166 } visitor;
2167
2168 visitor.fCodeGen = this;
2169 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002170 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002171}
2172
Ethan Nicholascc305772017-10-13 16:17:45 -04002173void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002174 switch (e.kind()) {
2175 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002176 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002177 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002178 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2179 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2180 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002181 if (-1 == builtin) {
2182 // normal var
2183 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002184 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002185 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2186 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002187 }
2188 break;
2189 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002190 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002191 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002192 break;
John Stilesdc75a972020-11-25 16:24:55 -05002193 case ProgramElement::Kind::kStructDefinition:
2194 // Handled in writeStructDefinitions. Do nothing.
2195 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002196 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002197 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002198 break;
John Stiles569249b2020-11-03 12:18:22 -05002199 case ProgramElement::Kind::kFunctionPrototype:
2200 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2201 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002202 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002203 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2204 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002205 this->writeLine(";");
2206 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002207 case ProgramElement::Kind::kEnum:
2208 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002209 default:
John Stileseada7bc2021-02-02 16:29:32 -05002210 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002211 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002212 }
2213}
2214
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002215MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2216 if (!e) {
2217 return kNo_Requirements;
2218 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002219 switch (e->kind()) {
2220 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002221 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002222 Requirements result = this->requirements(f.function());
2223 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002224 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002225 }
2226 return result;
2227 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002228 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002229 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04002230 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002231 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002232 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002233 }
2234 return result;
2235 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002236 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002237 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002238 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002239 return kGlobals_Requirement;
2240 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002241 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002242 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002243 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002244 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002245 case Expression::Kind::kBinary: {
2246 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002247 return this->requirements(bin.left().get()) |
2248 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002249 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002250 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002251 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002252 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002253 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002254 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002255 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002256 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002257 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002258 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002259 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002260 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2261 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002262 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002263 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002264 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002265 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002266 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002267 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002268 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002269 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002270 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002271 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002272 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002273 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002274 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002275 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002276 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002277 } else {
2278 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002279 }
2280 }
2281 return result;
2282 }
2283 default:
2284 return kNo_Requirements;
2285 }
2286}
2287
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002288MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2289 if (!s) {
2290 return kNo_Requirements;
2291 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002292 switch (s->kind()) {
2293 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002294 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002295 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002296 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002297 }
2298 return result;
2299 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002300 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002301 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002302 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002303 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002304 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002305 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002306 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002307 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002308 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002309 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002310 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002311 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002312 return this->requirements(i.test().get()) |
2313 this->requirements(i.ifTrue().get()) |
2314 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002315 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002316 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002317 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002318 return this->requirements(f.initializer().get()) |
2319 this->requirements(f.test().get()) |
2320 this->requirements(f.next().get()) |
2321 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002322 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002323 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002324 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002325 return this->requirements(d.test().get()) |
2326 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002327 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002328 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002329 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002330 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002331 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2332 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002333 }
2334 return result;
2335 }
2336 default:
2337 return kNo_Requirements;
2338 }
2339}
2340
2341MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002342 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002343 return kNo_Requirements;
2344 }
2345 auto found = fRequirements.find(&f);
2346 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002347 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002348 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002349 if (e->is<FunctionDefinition>()) {
2350 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002351 if (&def.declaration() == &f) {
2352 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002353 fRequirements[&f] = reqs;
2354 return reqs;
2355 }
2356 }
2357 }
John Stiles569249b2020-11-03 12:18:22 -05002358 // We never found a definition for this declared function, but it's legal to prototype a
2359 // function without ever giving a definition, as long as you don't call it.
2360 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002361 }
2362 return found->second;
2363}
2364
Timothy Liangb8eeb802018-07-23 16:46:16 -04002365bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002366 StringStream header;
2367 {
2368 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002369 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002370 this->writeStructDefinitions();
2371 this->writeUniformStruct();
2372 this->writeInputStruct();
2373 this->writeOutputStruct();
2374 this->writeInterfaceBlocks();
2375 this->writeGlobalStruct();
2376 }
2377 StringStream body;
2378 {
2379 AutoOutputStream outputToBody(this, &body, &fIndentation);
2380 for (const ProgramElement* e : fProgram.elements()) {
2381 this->writeProgramElement(*e);
2382 }
2383 }
2384 write_stringstream(header, *fOut);
2385 write_stringstream(fExtraFunctions, *fOut);
2386 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002387 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002388}
2389
John Stilesa6841be2020-08-06 14:11:56 -04002390} // namespace SkSL