blob: 60148cd5474cd20d7e6b0f1328732d6462ad9894 [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"
John Stiles7384b372021-04-01 13:48:15 -040013#include "src/sksl/ir/SkSLConstructorArray.h"
14#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050015#include "src/sksl/ir/SkSLExpressionStatement.h"
16#include "src/sksl/ir/SkSLExtension.h"
17#include "src/sksl/ir/SkSLIndexExpression.h"
18#include "src/sksl/ir/SkSLModifiersDeclaration.h"
19#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050020#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050021#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040022
Brian Osmanc262a122020-08-06 16:34:34 -040023#include <algorithm>
24
Ethan Nicholascc305772017-10-13 16:17:45 -040025namespace SkSL {
26
John Stiles45990502021-02-16 10:55:27 -050027const char* MetalCodeGenerator::OperatorName(Operator op) {
28 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050029 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050030 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050031 }
32}
33
John Stilescdcdb042020-07-06 09:03:51 -040034class MetalCodeGenerator::GlobalStructVisitor {
35public:
36 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050037 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
38 virtual void visitTexture(const Type& type, const String& name) = 0;
39 virtual void visitSampler(const Type& type, const String& name) = 0;
40 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040041};
42
Timothy Liangee84fe12018-05-18 14:38:19 -040043void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050044 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
45 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
46 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
47 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
48 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
49 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
50 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
51 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
52 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
53 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
54 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
55 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
56 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
57 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
58 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
59 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
60 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
61 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
62 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
63 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
64 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
65 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
66 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
67 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
68 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
69 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
70 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
71 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
72 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050073 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050074 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040075}
76
Ethan Nicholascc305772017-10-13 16:17:45 -040077void MetalCodeGenerator::write(const char* s) {
78 if (!s[0]) {
79 return;
80 }
81 if (fAtLineStart) {
82 for (int i = 0; i < fIndentation; i++) {
83 fOut->writeText(" ");
84 }
85 }
86 fOut->writeText(s);
87 fAtLineStart = false;
88}
89
90void MetalCodeGenerator::writeLine(const char* s) {
91 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050092 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040093}
94
95void MetalCodeGenerator::write(const String& s) {
96 this->write(s.c_str());
97}
98
99void MetalCodeGenerator::writeLine(const String& s) {
100 this->writeLine(s.c_str());
101}
102
103void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500104 fOut->writeText(fLineEnding);
105 fAtLineStart = true;
106}
107
108void MetalCodeGenerator::finishLine() {
109 if (!fAtLineStart) {
110 this->writeLine();
111 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400112}
113
114void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400115 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400116}
117
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500118String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400119 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500120 case Type::TypeKind::kArray:
121 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
122 return String::printf("array<%s, %d>",
123 this->typeName(type.componentType()).c_str(), type.columns());
124
Ethan Nicholase6592142020-09-08 10:22:09 -0400125 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500126 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500127
Ethan Nicholase6592142020-09-08 10:22:09 -0400128 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500129 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
130 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500131
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500133 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500134
John Stilesfd41d872020-11-25 22:39:45 -0500135 case Type::TypeKind::kEnum:
136 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500137
Ethan Nicholascc305772017-10-13 16:17:45 -0400138 default:
John Stiles54e7c052021-01-11 14:22:36 -0500139 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400140 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500141 return fContext.fTypes.fFloat->name();
142 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500143 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500144 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500145 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400146 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500147 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400148 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400149 }
150}
151
Brian Osman02bc5222021-01-28 11:00:20 -0500152void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
153 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500154 this->writeLine("struct " + type.name() + " {");
155 fIndentation++;
156 this->writeFields(type.fields(), type.fOffset);
157 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500158 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500159}
160
John Stilesb4418502021-02-04 10:57:08 -0500161void MetalCodeGenerator::writeType(const Type& type) {
162 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500163}
164
Ethan Nicholascc305772017-10-13 16:17:45 -0400165void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400166 switch (expr.kind()) {
167 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400168 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
John Stiles7384b372021-04-01 13:48:15 -0400176 case Expression::Kind::kConstructorArray:
177 this->writeConstructorArray(expr.as<ConstructorArray>(), parentPrecedence);
178 break;
John Stilese1182782021-03-30 22:09:37 -0400179 case Expression::Kind::kConstructorDiagonalMatrix:
John Stiles933043b2021-03-31 15:23:16 -0400180 this->writeSingleArgumentConstructor(expr.as<ConstructorDiagonalMatrix>(),
John Stilese1182782021-03-30 22:09:37 -0400181 parentPrecedence);
182 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400183 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400184 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400185 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400186 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400187 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400189 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400190 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400192 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400193 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400196 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400199 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400200 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400201 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400202 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400203 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400204 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400205 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400206 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400207 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400208 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400209 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400210 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400211 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400212 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400213 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400214 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400215 break;
216 default:
John Stileseada7bc2021-02-02 16:29:32 -0500217 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500218 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400219 }
220}
221
John Stiles06b84ef2020-12-09 12:35:48 -0500222String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
223 const ExpressionArray& arguments,
224 const SkTArray<VariableReference*>& outVars) {
225 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
226 const FunctionDeclaration& function = call.function();
227
John Stilese1068342021-03-22 11:57:41 -0400228 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
229 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500230 const char* separator = "";
231
232 // Emit a prototype for the function we'll be calling through to in our helper.
233 if (!function.isBuiltin()) {
234 this->writeFunctionDeclaration(function);
235 this->writeLine(";");
236 }
237
238 // Synthesize a helper function that takes the same inputs as `function`, except in places where
239 // `outVars` is non-null; in those places, we take the type of the VariableReference.
240 //
241 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500242 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500243 this->write(" ");
244 this->write(name);
245 this->write("(");
246 this->writeFunctionRequirementParams(function, separator);
247
248 SkASSERT(outVars.size() == arguments.size());
249 SkASSERT(outVars.size() == function.parameters().size());
250
John Stiles73e2c892021-02-13 13:58:01 -0500251 // We need to detect cases where the caller passes the same variable as an out-param more than
252 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
253 // redundant input parameter entirely, and not give it any name.)
254 std::unordered_set<const Variable*> writtenVars;
255
John Stiles06b84ef2020-12-09 12:35:48 -0500256 for (int index = 0; index < arguments.count(); ++index) {
257 this->write(separator);
258 separator = ", ";
259
260 const Variable* param = function.parameters()[index];
261 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
262
263 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500264 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500265
266 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
267 this->write("&");
268 }
269 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500270 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
271 if (didInsert) {
272 this->write(" ");
273 fIgnoreVariableReferenceModifiers = true;
274 this->writeVariableReference(*outVars[index]);
275 fIgnoreVariableReferenceModifiers = false;
276 }
John Stiles06b84ef2020-12-09 12:35:48 -0500277 } else {
278 this->write(" _var");
279 this->write(to_string(index));
280 }
John Stiles06b84ef2020-12-09 12:35:48 -0500281 }
282 this->writeLine(") {");
283
284 ++fIndentation;
285 for (int index = 0; index < outVars.count(); ++index) {
286 if (!outVars[index]) {
287 continue;
288 }
289 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500290 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500291 this->write(" _var");
292 this->write(to_string(index));
293
294 const Variable* param = function.parameters()[index];
295 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
296 this->write(" = ");
297 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500298 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500299 fIgnoreVariableReferenceModifiers = false;
300 }
301
302 this->writeLine(";");
303 }
304
John Stilesf7410bd2021-01-19 13:07:55 -0500305 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500306 bool hasResult = (call.type().name() != "void");
307 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500308 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500309 this->write(" _skResult = ");
310 }
311
John Stilese1068342021-03-22 11:57:41 -0400312 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500313 this->write("(");
314 separator = "";
315 this->writeFunctionRequirementArgs(function, separator);
316
317 for (int index = 0; index < arguments.count(); ++index) {
318 this->write(separator);
319 separator = ", ";
320
321 this->write("_var");
322 this->write(to_string(index));
323 }
324 this->writeLine(");");
325
326 for (int index = 0; index < outVars.count(); ++index) {
327 if (!outVars[index]) {
328 continue;
329 }
330 // outParam.zyx = _var2;
331 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500332 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500333 fIgnoreVariableReferenceModifiers = false;
334 this->write(" = _var");
335 this->write(to_string(index));
336 this->writeLine(";");
337 }
338
339 if (hasResult) {
340 this->writeLine("return _skResult;");
341 }
342
343 --fIndentation;
344 this->writeLine("}");
345
346 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500347}
348
John Stilesf64e4072020-12-10 10:34:27 -0500349String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
350 return "as_type<" + outType.displayName() + ">";
351}
352
Ethan Nicholascc305772017-10-13 16:17:45 -0400353void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400354 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500355 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
356 // special handling.
357 if (function.isBuiltin() && !function.definition()) {
358 auto iter = fIntrinsicMap.find(function.name());
359 if (iter != fIntrinsicMap.end()) {
360 this->writeIntrinsicCall(c, iter->second);
361 return;
362 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400363 }
John Stilesb21fac22020-12-04 15:36:49 -0500364
John Stilesd7199b22020-12-30 16:22:58 -0500365 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
366 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
367 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
368 // allow a swizzle to be passed to a `floatN&`.)
369 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500370 const std::vector<const Variable*>& parameters = function.parameters();
371 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500372
373 bool foundOutParam = false;
374 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500375 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500376
377 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500378 // If this is an out parameter...
379 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500380 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500381 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500382 // Assignability was verified at IRGeneration time, so this should always succeed.
383 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
384 outVars[index] = info.fAssignedVar;
385 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500386 }
387 }
388
John Stiles06b84ef2020-12-09 12:35:48 -0500389 if (foundOutParam) {
390 // Out parameters need to be written back to at the end of the function. To do this, we
391 // synthesize a helper function which evaluates the out-param expression into a temporary
392 // variable, calls the original function, then writes the temp var back into the out param
393 // using the original out-param expression. (This lets us support things like swizzles and
394 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500395 this->write(getOutParamHelper(c, arguments, outVars));
396 } else {
John Stilese1068342021-03-22 11:57:41 -0400397 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500398 }
399
Ethan Nicholascc305772017-10-13 16:17:45 -0400400 this->write("(");
401 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500402 this->writeFunctionRequirementArgs(function, separator);
403 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400404 this->write(separator);
405 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500406
407 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500408 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500409 } else {
Brian Osman00185012021-02-04 16:07:11 -0500410 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500411 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400412 }
413 this->write(")");
414}
415
Brian Osman964f0a02020-12-29 10:15:22 -0500416static constexpr char kInverse2x2[] = R"(
417float2x2 float2x2_inverse(float2x2 m) {
418 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
419}
420)";
421
422static constexpr char kInverse3x3[] = R"(
423float3x3 float3x3_inverse(float3x3 m) {
424 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
425 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
426 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
427 float b01 = a22*a11 - a12*a21;
428 float b11 = -a22*a10 + a12*a20;
429 float b21 = a21*a10 - a11*a20;
430 float det = a00*b01 + a01*b11 + a02*b21;
431 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
432 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
433 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
434}
435)";
436
437static constexpr char kInverse4x4[] = R"(
438float4x4 float4x4_inverse(float4x4 m) {
439 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
440 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
441 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
442 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
443 float b00 = a00*a11 - a01*a10;
444 float b01 = a00*a12 - a02*a10;
445 float b02 = a00*a13 - a03*a10;
446 float b03 = a01*a12 - a02*a11;
447 float b04 = a01*a13 - a03*a11;
448 float b05 = a02*a13 - a03*a12;
449 float b06 = a20*a31 - a21*a30;
450 float b07 = a20*a32 - a22*a30;
451 float b08 = a20*a33 - a23*a30;
452 float b09 = a21*a32 - a22*a31;
453 float b10 = a21*a33 - a23*a31;
454 float b11 = a22*a33 - a23*a32;
455 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
456 return float4x4(a11*b11 - a12*b10 + a13*b09,
457 a02*b10 - a01*b11 - a03*b09,
458 a31*b05 - a32*b04 + a33*b03,
459 a22*b04 - a21*b05 - a23*b03,
460 a12*b08 - a10*b11 - a13*b07,
461 a00*b11 - a02*b08 + a03*b07,
462 a32*b02 - a30*b05 - a33*b01,
463 a20*b05 - a22*b02 + a23*b01,
464 a10*b10 - a11*b08 + a13*b06,
465 a01*b08 - a00*b10 - a03*b06,
466 a30*b04 - a31*b02 + a33*b00,
467 a21*b02 - a20*b04 - a23*b00,
468 a11*b07 - a10*b09 - a12*b06,
469 a00*b09 - a01*b07 + a02*b06,
470 a31*b01 - a30*b03 - a32*b00,
471 a20*b03 - a21*b01 + a22*b00) * (1/det);
472}
473)";
474
John Stilesd7199b22020-12-30 16:22:58 -0500475String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
476 // Only use polyfills for a function taking a single-argument square matrix.
477 if (arguments.size() == 1) {
478 const Type& type = arguments.front()->type();
479 if (type.isMatrix() && type.rows() == type.columns()) {
480 // Inject the correct polyfill based on the matrix size.
481 String name = this->typeName(type) + "_inverse";
482 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
483 if (didInsert) {
484 switch (type.rows()) {
485 case 2:
486 fExtraFunctions.writeText(kInverse2x2);
487 break;
488 case 3:
489 fExtraFunctions.writeText(kInverse3x3);
490 break;
491 case 4:
492 fExtraFunctions.writeText(kInverse4x4);
493 break;
494 }
495 }
496 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500497 }
498 }
John Stilesd7199b22020-12-30 16:22:58 -0500499 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
500 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500501}
502
Brian Osman93aed9a2020-12-28 15:18:46 -0500503static constexpr char kMatrixCompMult[] = R"(
504template <int C, int R>
505matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
506 matrix<float, C, R> result;
507 for (int c = 0; c < C; ++c) {
508 result[c] = a[c] * b[c];
509 }
510 return result;
511}
512)";
513
514void MetalCodeGenerator::writeMatrixCompMult() {
515 String name = "matrixCompMult";
516 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
517 fWrittenIntrinsics.insert(name);
518 fExtraFunctions.writeText(kMatrixCompMult);
519 }
520}
521
John Stiles86424eb2020-12-11 11:17:14 -0500522String MetalCodeGenerator::getTempVariable(const Type& type) {
523 String tempVar = "_skTemp" + to_string(fVarCount++);
524 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
525 return tempVar;
526}
527
John Stiles791c27d2020-12-30 14:56:57 -0500528void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
529 // Write out an intrinsic function call exactly as-is. No muss no fuss.
530 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500531 this->writeArgumentList(c.arguments());
532}
533
534void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500535 this->write("(");
536 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500537 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500538 this->write(separator);
539 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500540 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500541 }
542 this->write(")");
543}
544
John Stilesd7199b22020-12-30 16:22:58 -0500545void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400546 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400547 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500548 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500549 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400550 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500551 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400552 this->write(SAMPLER_SUFFIX);
553 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400554 const Type& arg1Type = arguments[1]->type();
John Stiles54e7c052021-01-11 14:22:36 -0500555 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500556 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500557 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500558 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500559 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500560 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400561 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500562 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Brian Osman00185012021-02-04 16:07:11 -0500563 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400564 this->write(")");
565 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400566 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400567 }
John Stilesd7199b22020-12-30 16:22:58 -0500568 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400569 // 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 -0500570 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500571 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500572 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500573 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500574 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500575 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500576 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400577 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500578 }
Brian Osman46787d52020-11-24 14:18:23 -0500579 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500580 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500581 if (arguments[0]->type().columns() == 1) {
582 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500583 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500584 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500585 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500586 this->write(")");
587 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500588 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500589 }
590 break;
591 }
John Stilesd7199b22020-12-30 16:22:58 -0500592 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500593 if (arguments[0]->type().columns() == 1) {
594 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500595 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500596 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500597 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500598 this->write(")");
599 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500600 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500601 }
602 break;
603 }
John Stilesd7199b22020-12-30 16:22:58 -0500604 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500605 if (arguments[0]->type().columns() == 1) {
606 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
607 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500608 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500609 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500610 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500611 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500612 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500613 this->write("))");
614 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500615 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500616 }
617 break;
618 }
John Stilesd7199b22020-12-30 16:22:58 -0500619 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500620 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500621 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500622 this->write(")");
623 break;
624 }
John Stilesd7199b22020-12-30 16:22:58 -0500625 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500626 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500627 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500628 this->write(")");
629 break;
630 }
John Stilesd7199b22020-12-30 16:22:58 -0500631 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500632 this->write(this->getBitcastIntrinsic(c.type()));
633 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500634 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500635 this->write(")");
636 break;
637 }
John Stilesd7199b22020-12-30 16:22:58 -0500638 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500639 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500640 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500641 this->write(") * 57.2957795)");
642 break;
643 }
John Stilesd7199b22020-12-30 16:22:58 -0500644 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500645 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500646 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500647 this->write(") * 0.0174532925)");
648 break;
649 }
John Stilesd7199b22020-12-30 16:22:58 -0500650 case kDFdx_IntrinsicKind: {
651 this->write("dfdx");
652 this->writeArgumentList(c.arguments());
653 break;
654 }
655 case kDFdy_IntrinsicKind: {
656 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500657 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500658 this->write("-");
659 }
660 this->write("dfdy");
661 this->writeArgumentList(c.arguments());
662 break;
663 }
664 case kInverse_IntrinsicKind: {
665 this->write(this->getInversePolyfill(arguments));
666 this->writeArgumentList(c.arguments());
667 break;
668 }
669 case kInversesqrt_IntrinsicKind: {
670 this->write("rsqrt");
671 this->writeArgumentList(c.arguments());
672 break;
673 }
674 case kAtan_IntrinsicKind: {
675 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
676 this->writeArgumentList(c.arguments());
677 break;
678 }
679 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500680 if (arguments[0]->type().columns() == 1) {
681 // We need to synthesize `I - 2 * N * I * N`.
682 String tmpI = this->getTempVariable(arguments[0]->type());
683 String tmpN = this->getTempVariable(arguments[1]->type());
684
685 // (_skTempI = ...
686 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500687 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500688
689 // , _skTempN = ...
690 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500691 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500692
693 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
694 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
695 } else {
696 this->writeSimpleIntrinsic(c);
697 }
698 break;
699 }
John Stilesd7199b22020-12-30 16:22:58 -0500700 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500701 if (arguments[0]->type().columns() == 1) {
702 // Metal does implement refract for vectors; rather than reimplementing refract from
703 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
704 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500705 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500706 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500707 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500708 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500709 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500710 this->write(").x)");
711 } else {
712 this->writeSimpleIntrinsic(c);
713 }
714 break;
715 }
John Stiles23456532020-12-30 18:12:48 -0500716 case kRoundEven_IntrinsicKind: {
717 this->write("rint");
718 this->writeArgumentList(c.arguments());
719 break;
720 }
John Stilesd7199b22020-12-30 16:22:58 -0500721 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500722 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500723 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500724 this->write(")");
725 break;
726 }
John Stilesd7199b22020-12-30 16:22:58 -0500727 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500728 // Create a temp variable to store the expression, to avoid double-evaluating it.
729 String skTemp = this->getTempVariable(arguments[0]->type());
730 String exprType = this->typeName(arguments[0]->type());
731
732 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
733 // Use select to detect zero inputs and force a -1 result.
734
735 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
736 this->write("(");
737 this->write(skTemp);
738 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500739 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500740 this->write("), select(ctz(");
741 this->write(skTemp);
742 this->write("), ");
743 this->write(exprType);
744 this->write("(-1), ");
745 this->write(skTemp);
746 this->write(" == ");
747 this->write(exprType);
748 this->write("(0)))");
749 break;
750 }
John Stilesd7199b22020-12-30 16:22:58 -0500751 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500752 // Create a temp variable to store the expression, to avoid double-evaluating it.
753 String skTemp1 = this->getTempVariable(arguments[0]->type());
754 String exprType = this->typeName(arguments[0]->type());
755
756 // GLSL findMSB is actually quite different from Metal's clz:
757 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
758 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
759
760 // (_skTemp1 = (.....),
761 this->write("(");
762 this->write(skTemp1);
763 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500764 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500765 this->write("), ");
766
767 // Signed input types might be negative; we need another helper variable to negate the
768 // input (since we can only find one bits, not zero bits).
769 String skTemp2;
770 if (arguments[0]->type().isSigned()) {
771 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
772 skTemp2 = this->getTempVariable(arguments[0]->type());
773 this->write(skTemp2);
774 this->write(" = (select(");
775 this->write(skTemp1);
776 this->write(", ~");
777 this->write(skTemp1);
778 this->write(", ");
779 this->write(skTemp1);
780 this->write(" < 0)), ");
781 } else {
782 skTemp2 = skTemp1;
783 }
784
785 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
786 this->write("select(");
787 this->write(this->typeName(c.type()));
788 this->write("(clz(");
789 this->write(skTemp2);
790 this->write(")), ");
791 this->write(this->typeName(c.type()));
792 this->write("(-1), ");
793 this->write(skTemp2);
794 this->write(" == ");
795 this->write(exprType);
796 this->write("(0)))");
797 break;
798 }
John Stilesd7199b22020-12-30 16:22:58 -0500799 case kMatrixCompMult_IntrinsicKind: {
800 this->writeMatrixCompMult();
801 this->writeSimpleIntrinsic(c);
802 break;
803 }
804 case kCompareEqual_IntrinsicKind:
805 case kCompareGreaterThan_IntrinsicKind:
806 case kCompareGreaterThanEqual_IntrinsicKind:
807 case kCompareLessThan_IntrinsicKind:
808 case kCompareLessThanEqual_IntrinsicKind:
809 case kCompareNotEqual_IntrinsicKind: {
810 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500811 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500812 switch (kind) {
813 case kCompareEqual_IntrinsicKind:
814 this->write(" == ");
815 break;
816 case kCompareNotEqual_IntrinsicKind:
817 this->write(" != ");
818 break;
819 case kCompareLessThan_IntrinsicKind:
820 this->write(" < ");
821 break;
822 case kCompareLessThanEqual_IntrinsicKind:
823 this->write(" <= ");
824 break;
825 case kCompareGreaterThan_IntrinsicKind:
826 this->write(" > ");
827 break;
828 case kCompareGreaterThanEqual_IntrinsicKind:
829 this->write(" >= ");
830 break;
831 default:
John Stilesf57207b2021-02-02 17:50:34 -0500832 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500833 }
Brian Osman00185012021-02-04 16:07:11 -0500834 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500835 this->write(")");
836 break;
837 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400838 default:
John Stilesf57207b2021-02-02 17:50:34 -0500839 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400840 }
841}
842
John Stilesfcf8cb22020-08-06 14:29:22 -0400843// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
844// Cells that don't exist in the source matrix will be populated with identity-matrix values.
845void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
846 SkASSERT(rows <= 4);
847 SkASSERT(columns <= 4);
848
849 const char* columnSeparator = "";
850 for (int c = 0; c < columns; ++c) {
851 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
852 columnSeparator = "), ";
853
854 // Determine how many values to take from the source matrix for this row.
855 int swizzleLength = 0;
856 if (c < sourceMatrix.columns()) {
857 swizzleLength = std::min<>(rows, sourceMatrix.rows());
858 }
859
860 // Emit all the values from the source matrix row.
861 bool firstItem;
862 switch (swizzleLength) {
863 case 0: firstItem = true; break;
864 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
865 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
866 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
867 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
868 default: SkUNREACHABLE;
869 }
870
871 // Emit the placeholder identity-matrix cells.
872 for (int r = swizzleLength; r < rows; ++r) {
873 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
874 firstItem = false;
875 }
876 }
877
878 fExtraFunctions.writeText(")");
879}
880
881// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
882// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400883void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
884 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400885 size_t argIndex = 0;
886 int argPosition = 0;
887
888 const char* columnSeparator = "";
889 for (int c = 0; c < columns; ++c) {
890 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
891 columnSeparator = "), ";
892
893 const char* rowSeparator = "";
894 for (int r = 0; r < rows; ++r) {
895 fExtraFunctions.writeText(rowSeparator);
896 rowSeparator = ", ";
897
898 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400899 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400900 switch (argType.typeKind()) {
901 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400902 fExtraFunctions.printf("x%zu", argIndex);
903 break;
904 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400905 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400906 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
907 break;
908 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400909 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400910 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
911 argPosition / argType.rows(),
912 argPosition % argType.rows());
913 break;
914 }
915 default: {
916 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
917 fExtraFunctions.writeText("<error>");
918 break;
919 }
920 }
921
922 ++argPosition;
923 if (argPosition >= argType.columns() * argType.rows()) {
924 ++argIndex;
925 argPosition = 0;
926 }
927 } else {
928 SkDEBUGFAIL("not enough arguments for matrix constructor");
929 fExtraFunctions.writeText("<error>");
930 }
931 }
932 }
933
934 if (argPosition != 0 || argIndex != args.size()) {
935 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
936 fExtraFunctions.writeText(", <error>");
937 }
938
939 fExtraFunctions.writeText(")");
940}
941
John Stiles1bdafbf2020-05-28 12:17:20 -0400942// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
943// Keeps track of previously generated constructors so that we won't generate more than one
944// constructor for any given permutation of input argument types. Returns the name of the
945// generated constructor method.
946String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400947 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500948 int columns = matrix.columns();
949 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400950 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400951
952 // Create the helper-method name and use it as our lookup key.
953 String name;
954 name.appendf("float%dx%d_from", columns, rows);
955 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500956 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400957 }
958
959 // If a helper-method has already been synthesized, we don't need to synthesize it again.
960 auto [iter, newlyCreated] = fHelpers.insert(name);
961 if (!newlyCreated) {
962 return name;
963 }
964
965 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
966 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
967 // supply a mixture of scalars and vectors.)
968 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
969
970 size_t argIndex = 0;
971 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400972 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400973 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500974 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400975 argSeparator = ", ";
976 }
977
978 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
979
John Stiles9aeed132020-11-24 17:36:06 -0500980 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400981 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400982 } else {
983 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400984 }
985
John Stilesfcf8cb22020-08-06 14:29:22 -0400986 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500987 return name;
988}
989
990bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
991 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
992 return false;
993 }
994 if (t1.columns() > 1) {
995 return this->canCoerce(t1.componentType(), t2.componentType());
996 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500997 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500998}
999
John Stiles1bdafbf2020-05-28 12:17:20 -04001000bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
1001 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -05001002 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001003 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001004 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001005
1006 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1007 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1008 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1009 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1010 // that converts our inputs into a properly-shaped matrix.
1011 // A matrix construct helper method is always used if any input argument is a matrix.
1012 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1013 //
1014 // float2 x = (1, 2);
1015 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1016 // | 2 4 6 |
1017 //
1018 // float2 x = (2, 3);
1019 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1020 // | 2 4 6 |
1021 //
1022 // float4 x = (1, 2, 3, 4);
1023 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1024 // | 2 4 |
1025 //
1026
1027 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001028 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001029 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001030 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001031 return true;
1032 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001033 position += expr->type().columns();
1034 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001035 // An input argument would span multiple rows; a helper function is required.
1036 return true;
1037 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001038 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001039 // We've advanced to the end of a row. Wrap to the start of the next row.
1040 position = 0;
1041 }
1042 }
1043
1044 return false;
1045}
1046
1047void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001048 const Type& constructorType = c.type();
John Stiles7384b372021-04-01 13:48:15 -04001049 SkASSERT(!constructorType.isArray());
1050
John Stiles1bdafbf2020-05-28 12:17:20 -04001051 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001052 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001053 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001054 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001055 const Type& argType = arg.type();
1056 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001057 this->writeExpression(arg, parentPrecedence);
1058 return;
1059 }
1060
1061 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
1062 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -05001063 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001064 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -04001065 this->write("float");
1066 this->write(to_string(matrix.columns()));
1067 this->write("x");
1068 this->write(to_string(matrix.rows()));
1069 this->write("(");
1070 this->writeExpression(arg, parentPrecedence);
1071 this->write(")");
1072 return;
1073 }
1074 }
1075
1076 // Emit and invoke a matrix-constructor helper method if one is necessary.
1077 if (this->matrixConstructHelperIsNeeded(c)) {
1078 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001079 this->write("(");
1080 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001081 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001082 this->write(separator);
1083 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001084 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001085 }
John Stiles1fa15b12020-05-28 17:36:54 +00001086 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001087 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001088 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001089
1090 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stilesb4418502021-02-04 10:57:08 -05001091 this->writeType(constructorType);
John Stiles7384b372021-04-01 13:48:15 -04001092 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001093 const char* separator = "";
1094 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001095 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001096 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001097 this->write(separator);
1098 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001099 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001100 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001101 // Merge scalars and smaller vectors together.
1102 if (!scalarCount) {
John Stilesb4418502021-02-04 10:57:08 -05001103 this->writeType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001104 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001105 this->write("(");
1106 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001107 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001108 }
Brian Osman00185012021-02-04 16:07:11 -05001109 this->writeExpression(*arg, Precedence::kSequence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001110 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001111 this->write(")");
1112 scalarCount = 0;
1113 }
1114 }
John Stiles7384b372021-04-01 13:48:15 -04001115 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001116}
1117
John Stiles933043b2021-03-31 15:23:16 -04001118void MetalCodeGenerator::writeSingleArgumentConstructor(const SingleArgumentConstructor& c,
John Stilese1182782021-03-30 22:09:37 -04001119 Precedence parentPrecedence) {
1120 this->writeType(c.type());
1121 this->write("(");
1122 this->writeExpression(*c.argument(), Precedence::kSequence);
1123 this->write(")");
1124}
1125
John Stiles7384b372021-04-01 13:48:15 -04001126void MetalCodeGenerator::writeConstructorArray(const ConstructorArray& c,
1127 Precedence parentPrecedence) {
1128 this->writeType(c.type());
1129 this->write("{");
1130 const char* separator = "";
1131 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
1132 this->write(separator);
1133 separator = ", ";
1134 this->writeExpression(*arg, Precedence::kSequence);
1135 }
1136 this->write("}");
1137}
1138
Ethan Nicholascc305772017-10-13 16:17:45 -04001139void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001140 if (fRTHeightName.length()) {
1141 this->write("float4(_fragCoord.x, ");
1142 this->write(fRTHeightName.c_str());
1143 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001144 } else {
1145 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1146 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001147}
1148
1149void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001150 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001151 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001152 // we're actually targeting the clones.
1153 if (fIgnoreVariableReferenceModifiers) {
1154 this->writeName(ref.variable()->name());
1155 return;
1156 }
1157
Ethan Nicholas78686922020-10-08 06:46:27 -04001158 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001159 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001160 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001161 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001162 case SK_FRAGCOORD_BUILTIN:
1163 this->writeFragCoord();
1164 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001165 case SK_VERTEXID_BUILTIN:
1166 this->write("sk_VertexID");
1167 break;
1168 case SK_INSTANCEID_BUILTIN:
1169 this->write("sk_InstanceID");
1170 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001171 case SK_CLOCKWISE_BUILTIN:
1172 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001173 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001174 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001175 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001176 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001177 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001178 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001179 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001180 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001181 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001182 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001183 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1184 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001185 this->write("_uniforms.");
1186 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001187 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001188 }
1189 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001190 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001191 }
1192}
1193
1194void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001195 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001196 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001197 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001198 this->write("]");
1199}
1200
1201void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001202 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1203 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001204 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001205 this->write(".");
1206 }
Timothy Liang7d637782018-06-05 09:58:07 -04001207 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001208 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001209 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001210 break;
1211 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001212 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001213 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001214 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001215 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001216 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001217 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1218 this->write("->");
1219 }
Timothy Liang651286f2018-06-07 09:55:33 -04001220 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001221 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001222 }
1223}
1224
1225void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001226 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001227 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001228 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001229 SkASSERT(c >= 0 && c <= 3);
1230 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001231 }
1232}
1233
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001234void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1235 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001236 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001237
1238 auto [iter, wasInserted] = fHelpers.insert(key);
1239 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001240 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001241 " left = left * right;\n"
1242 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001243 "}\n",
1244 this->typeName(result).c_str(), this->typeName(left).c_str(),
1245 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001246 }
1247}
1248
John Stiles01cdf012021-02-10 09:53:41 -05001249void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1250 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1251 left.description().c_str(), right.description().c_str());
1252
1253 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1254
1255 auto [iter, wasInserted] = fHelpers.insert(key);
1256 if (wasInserted) {
1257 fExtraFunctions.printf(
1258 "thread bool operator==(const %s left, const %s right) {\n"
1259 " return",
1260 this->typeName(left).c_str(), this->typeName(right).c_str());
1261
1262 for (int index=0; index<left.columns(); ++index) {
1263 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1264 index == 0 ? "" : " &&", index, index);
1265 }
1266 fExtraFunctions.printf(";\n"
1267 "}\n");
1268 }
1269}
1270
1271void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1272 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1273 left.description().c_str(), right.description().c_str());
1274
1275 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1276
1277 auto [iter, wasInserted] = fHelpers.insert(key);
1278 if (wasInserted) {
1279 fExtraFunctions.printf(
1280 "thread bool operator!=(const %s left, const %s right) {\n"
1281 " return",
1282 this->typeName(left).c_str(), this->typeName(right).c_str());
1283
1284 for (int index=0; index<left.columns(); ++index) {
1285 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1286 index == 0 ? "" : " ||", index, index);
1287 }
1288 fExtraFunctions.printf(";\n"
1289 "}\n");
1290 }
1291}
1292
Ethan Nicholascc305772017-10-13 16:17:45 -04001293void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1294 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001295 const Expression& left = *b.left();
1296 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001297 const Type& leftType = left.type();
1298 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001299 Operator op = b.getOperator();
1300 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001301 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001302 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001303 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001304 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001305 this->write("all");
1306 needParens = true;
1307 }
1308 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001309 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001310 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001311 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001312 needParens = true;
1313 }
1314 break;
1315 default:
1316 break;
1317 }
1318 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001319 this->write("(");
1320 }
John Stiles01cdf012021-02-10 09:53:41 -05001321 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001322 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001323 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001324 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001325 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001326 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001327 this->writeMatrixInequalityHelper(leftType, rightType);
1328 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001329 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001330 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001331 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001332 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001333 // This doesn't compile in Metal:
1334 // float4 x = float4(1);
1335 // x.xy *= float2x2(...);
1336 // with the error message "non-const reference cannot bind to vector element",
1337 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1338 // as long as the LHS has no side effects, and hope for the best otherwise.
1339 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001340 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001341 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001342 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001343 SkASSERT(opName.endsWith("="));
1344 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001345 this->write(" ");
1346 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001347 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001348 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001349 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001350 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001351 this->write(")");
1352 }
1353}
1354
1355void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1356 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001357 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001358 this->write("(");
1359 }
Brian Osman00185012021-02-04 16:07:11 -05001360 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001361 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001362 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001363 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001364 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1365 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001366 this->write(")");
1367 }
1368}
1369
1370void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1371 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001372 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001373 this->write("(");
1374 }
John Stilesd6449e92020-11-30 09:13:23 -05001375 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001376 this->writeExpression(*p.operand(), Precedence::kPrefix);
1377 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001378 this->write(")");
1379 }
1380}
1381
1382void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1383 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001384 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001385 this->write("(");
1386 }
Brian Osman00185012021-02-04 16:07:11 -05001387 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001388 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001389 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001390 this->write(")");
1391 }
1392}
1393
1394void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001395 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001396}
1397
1398void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001399 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001400 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001401 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001402 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001403 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001404 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001405 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001406 } else {
John Stiles12739df2020-12-29 09:47:20 -05001407 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001408 }
1409}
1410
1411void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001412 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001413}
1414
1415void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001416 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001417}
1418
John Stiles06b84ef2020-12-09 12:35:48 -05001419void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1420 const char*& separator) {
1421 Requirements requirements = this->requirements(f);
1422 if (requirements & kInputs_Requirement) {
1423 this->write(separator);
1424 this->write("_in");
1425 separator = ", ";
1426 }
1427 if (requirements & kOutputs_Requirement) {
1428 this->write(separator);
1429 this->write("_out");
1430 separator = ", ";
1431 }
1432 if (requirements & kUniforms_Requirement) {
1433 this->write(separator);
1434 this->write("_uniforms");
1435 separator = ", ";
1436 }
1437 if (requirements & kGlobals_Requirement) {
1438 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001439 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001440 separator = ", ";
1441 }
1442 if (requirements & kFragCoord_Requirement) {
1443 this->write(separator);
1444 this->write("_fragCoord");
1445 separator = ", ";
1446 }
1447}
1448
1449void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1450 const char*& separator) {
1451 Requirements requirements = this->requirements(f);
1452 if (requirements & kInputs_Requirement) {
1453 this->write(separator);
1454 this->write("Inputs _in");
1455 separator = ", ";
1456 }
1457 if (requirements & kOutputs_Requirement) {
1458 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001459 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001460 separator = ", ";
1461 }
1462 if (requirements & kUniforms_Requirement) {
1463 this->write(separator);
1464 this->write("Uniforms _uniforms");
1465 separator = ", ";
1466 }
1467 if (requirements & kGlobals_Requirement) {
1468 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001469 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001470 separator = ", ";
1471 }
1472 if (requirements & kFragCoord_Requirement) {
1473 this->write(separator);
1474 this->write("float4 _fragCoord");
1475 separator = ", ";
1476 }
1477}
1478
John Stilesda5cdf62021-01-28 11:47:29 -05001479int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1480 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001481 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001482}
1483
1484int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1485 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001486 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001487}
1488
John Stiles569249b2020-11-03 12:18:22 -05001489bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001490 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001491 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001492 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001493 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001494 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001495 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001496 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001497 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001498 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001499 break;
1500 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001501 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001502 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001503 }
1504 this->write("(Inputs _in [[stage_in]]");
1505 if (-1 != fUniformBuffer) {
1506 this->write(", constant Uniforms& _uniforms [[buffer(" +
1507 to_string(fUniformBuffer) + ")]]");
1508 }
Brian Osman133724c2020-10-28 14:14:39 -04001509 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001510 if (e->is<GlobalVarDeclaration>()) {
1511 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001512 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1513 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1514 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001515 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001516 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001517 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001518 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001519 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001520 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001521 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001522 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001523 }
1524 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001525 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001526 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001527 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001528 this->write(")]]");
1529 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001530 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001531 this->write(SAMPLER_SUFFIX);
1532 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001533 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001534 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001535 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001536 } else if (e->is<InterfaceBlock>()) {
1537 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001538 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001539 continue;
1540 }
1541 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001542 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001543 this->write("& " );
1544 this->write(fInterfaceBlockNameMap[&intf]);
1545 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001546 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001547 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001548 }
1549 }
John Stiles270cec22021-02-17 12:59:36 -05001550 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001551 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001552 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001553 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001554 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001555 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001556 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001557 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001558 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001559 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001560 separator = ", ";
1561 } else {
John Stilesb4418502021-02-04 10:57:08 -05001562 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001563 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001564 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001565 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001566 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001567 }
John Stiles569249b2020-11-03 12:18:22 -05001568 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001569 this->write(separator);
1570 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001571 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001572 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001573 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001574 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001575 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001576 }
Timothy Liang651286f2018-06-07 09:55:33 -04001577 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001578 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001579 }
John Stiles569249b2020-11-03 12:18:22 -05001580 this->write(")");
1581 return true;
1582}
Ethan Nicholascc305772017-10-13 16:17:45 -04001583
John Stiles569249b2020-11-03 12:18:22 -05001584void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1585 this->writeFunctionDeclaration(f.declaration());
1586 this->writeLine(";");
1587}
1588
John Stiles986c7fb2020-12-01 14:44:56 -05001589static bool is_block_ending_with_return(const Statement* stmt) {
1590 // This function detects (potentially nested) blocks that end in a return statement.
1591 if (!stmt->is<Block>()) {
1592 return false;
1593 }
1594 const StatementArray& block = stmt->as<Block>().children();
1595 for (int index = block.count(); index--; ) {
1596 const Statement& stmt = *block[index];
1597 if (stmt.is<ReturnStatement>()) {
1598 return true;
1599 }
1600 if (stmt.is<Block>()) {
1601 return is_block_ending_with_return(&stmt);
1602 }
1603 if (!stmt.is<Nop>()) {
1604 break;
1605 }
1606 }
1607 return false;
1608}
1609
John Stiles569249b2020-11-03 12:18:22 -05001610void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001611 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001612
John Stiles569249b2020-11-03 12:18:22 -05001613 if (!this->writeFunctionDeclaration(f.declaration())) {
1614 return;
1615 }
1616
John Stiles986c7fb2020-12-01 14:44:56 -05001617 fCurrentFunction = &f.declaration();
1618 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1619
John Stiles569249b2020-11-03 12:18:22 -05001620 this->writeLine(" {");
1621
John Stilese8da4d22021-03-24 09:19:45 -04001622 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001623 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001624 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001625 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001626 }
John Stilesc67b3622020-05-28 17:53:13 -04001627
Ethan Nicholascc305772017-10-13 16:17:45 -04001628 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001629 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001630 {
1631 AutoOutputStream outputToBuffer(this, &buffer);
1632 fIndentation++;
1633 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1634 if (!stmt->isEmpty()) {
1635 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001636 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001637 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001638 }
John Stilese8da4d22021-03-24 09:19:45 -04001639 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001640 // If the main function doesn't end with a return, we need to synthesize one here.
1641 if (!is_block_ending_with_return(f.body().get())) {
1642 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001643 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001644 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001645 }
John Stiles44532372020-12-07 12:33:55 -05001646 fIndentation--;
1647 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001648 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001649 this->write(fFunctionHeader);
1650 this->write(buffer.str());
1651}
1652
1653void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001654 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001655 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1656 this->write("thread ");
1657 }
1658 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001659 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001660 }
1661}
1662
1663void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001664 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001665 return;
1666 }
John Stiles06b84ef2020-12-09 12:35:48 -05001667 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001668 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001669 this->writeLine(intf.typeName() + " {");
1670 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001671 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001672 structType = &structType->componentType();
1673 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001674 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001675 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001676 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001677 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 }
1679 fIndentation--;
1680 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001681 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001682 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001683 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001684 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001685 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001686 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001687 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001688 } else if (intf.arraySize() == Type::kUnsizedArray){
1689 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001690 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001691 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001692 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001693 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001694 }
1695 this->writeLine(";");
1696}
1697
Timothy Liangdc89f192018-06-13 09:20:31 -04001698void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1699 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001700 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001701 int currentOffset = 0;
1702 for (const auto& field: fields) {
1703 int fieldOffset = field.fModifiers.fLayout.fOffset;
1704 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001705 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001706 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1707 return;
1708 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001709 if (fieldOffset != -1) {
1710 if (currentOffset > fieldOffset) {
1711 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001712 "offset of field '" + field.fName + "' must be at least " +
1713 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001714 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001715 } else if (currentOffset < fieldOffset) {
1716 this->write("char pad");
1717 this->write(to_string(fPaddingCount++));
1718 this->write("[");
1719 this->write(to_string(fieldOffset - currentOffset));
1720 this->writeLine("];");
1721 currentOffset = fieldOffset;
1722 }
1723 int alignment = memoryLayout.alignment(*fieldType);
1724 if (fieldOffset % alignment) {
1725 fErrors.error(parentOffset,
1726 "offset of field '" + field.fName + "' must be a multiple of " +
1727 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001728 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001729 }
1730 }
Brian Osman8609a242020-09-08 14:01:49 -04001731 size_t fieldSize = memoryLayout.size(*fieldType);
1732 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1733 fErrors.error(parentOffset, "field offset overflow");
1734 return;
1735 }
1736 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001737 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001738 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001739 this->write(" ");
1740 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001741 this->writeLine(";");
1742 if (parentIntf) {
1743 fInterfaceBlockMap[&field] = parentIntf;
1744 }
1745 }
1746}
1747
Ethan Nicholascc305772017-10-13 16:17:45 -04001748void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001749 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001750}
1751
Timothy Liang651286f2018-06-07 09:55:33 -04001752void MetalCodeGenerator::writeName(const String& name) {
1753 if (fReservedWords.find(name) != fReservedWords.end()) {
1754 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1755 }
1756 this->write(name);
1757}
1758
John Stilesb4418502021-02-04 10:57:08 -05001759void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1760 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001761 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001762 }
John Stilesb4418502021-02-04 10:57:08 -05001763 this->writeModifiers(varDecl.var().modifiers(), global);
1764 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001765 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001766 this->writeName(varDecl.var().name());
1767 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001768 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001769 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001770 }
1771 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001772}
1773
1774void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001775 switch (s.kind()) {
1776 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001777 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001778 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001779 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001780 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001781 this->write(";");
1782 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001783 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001784 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001785 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001786 case Statement::Kind::kVarDeclaration:
1787 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001788 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001789 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001790 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001791 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001792 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001793 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001795 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001796 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001797 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001798 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001799 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001800 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001801 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001802 this->write("break;");
1803 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001804 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001805 this->write("continue;");
1806 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001807 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001808 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001809 break;
John Stiles98c1f822020-09-09 14:18:53 -04001810 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001811 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 this->write(";");
1813 break;
1814 default:
John Stileseada7bc2021-02-02 16:29:32 -05001815 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001816 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001817 }
1818}
1819
Ethan Nicholascc305772017-10-13 16:17:45 -04001820void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001821 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1822 // something here to make the code valid).
1823 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001824 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001825 this->writeLine("{");
1826 fIndentation++;
1827 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001828 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1829 if (!stmt->isEmpty()) {
1830 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001831 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001832 }
1833 }
1834 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001835 fIndentation--;
1836 this->write("}");
1837 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001838}
1839
1840void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1841 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001842 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001843 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001844 this->writeStatement(*stmt.ifTrue());
1845 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001846 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001847 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001848 }
1849}
1850
1851void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001852 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1853 if (!f.initializer() && f.test() && !f.next()) {
1854 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001855 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001856 this->write(") ");
1857 this->writeStatement(*f.statement());
1858 return;
1859 }
1860
Ethan Nicholascc305772017-10-13 16:17:45 -04001861 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001862 if (f.initializer() && !f.initializer()->isEmpty()) {
1863 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 } else {
1865 this->write("; ");
1866 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001867 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001868 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001869 }
1870 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001871 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001872 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001873 }
1874 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001875 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001876}
1877
Ethan Nicholascc305772017-10-13 16:17:45 -04001878void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1879 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001880 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001881 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001882 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001883 this->write(");");
1884}
1885
1886void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1887 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001888 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001889 this->writeLine(") {");
1890 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001891 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1892 const SwitchCase& c = stmt->as<SwitchCase>();
1893 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001894 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001895 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001896 this->writeLine(":");
1897 } else {
1898 this->writeLine("default:");
1899 }
John Stilesb23a64b2021-03-11 08:27:59 -05001900 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001901 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001902 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001903 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001904 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001905 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001906 }
1907 fIndentation--;
1908 this->write("}");
1909}
1910
John Stiles986c7fb2020-12-01 14:44:56 -05001911void MetalCodeGenerator::writeReturnStatementFromMain() {
1912 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001913 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001914 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001915 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001916 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001917 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001918 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001919 break;
1920 default:
1921 SkDEBUGFAIL("unsupported kind of program");
1922 }
1923}
1924
Ethan Nicholascc305772017-10-13 16:17:45 -04001925void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04001926 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001927 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001928 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1929 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001930 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001931 this->writeLine(";");
1932 } else {
1933 fErrors.error(r.fOffset, "Metal does not support returning '" +
1934 r.expression()->type().description() + "' from main()");
1935 }
John Stiles986c7fb2020-12-01 14:44:56 -05001936 }
1937 this->writeReturnStatementFromMain();
1938 return;
1939 }
1940
Ethan Nicholascc305772017-10-13 16:17:45 -04001941 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001942 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001943 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001944 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001945 }
1946 this->write(";");
1947}
1948
Michael Ludwigbf58add2021-03-16 10:40:11 -04001949void MetalCodeGenerator::writeHeader() {
1950 this->write("#include <metal_stdlib>\n");
1951 this->write("#include <simd/simd.h>\n");
1952 this->write("using namespace metal;\n");
1953}
1954
Ethan Nicholascc305772017-10-13 16:17:45 -04001955void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001956 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001957 if (e->is<GlobalVarDeclaration>()) {
1958 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001959 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001960 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001961 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001962 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001963 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001964 if (-1 == fUniformBuffer) {
1965 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001966 fUniformBuffer = uniformSet;
1967 } else if (uniformSet != fUniformBuffer) {
1968 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1969 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001970 }
1971 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001972 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001973 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001974 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001975 this->write(";\n");
1976 }
1977 }
1978 }
1979 if (-1 != fUniformBuffer) {
1980 this->write("};\n");
1981 }
1982}
1983
1984void MetalCodeGenerator::writeInputStruct() {
1985 this->write("struct Inputs {\n");
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::kIn_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());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001996 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05001997 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04001998 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001999 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002000 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002001 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002002 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002003 }
2004 }
2005 this->write(";\n");
2006 }
2007 }
2008 }
2009 this->write("};\n");
2010}
2011
2012void MetalCodeGenerator::writeOutputStruct() {
2013 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002014 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002015 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002016 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002017 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002018 }
Brian Osman133724c2020-10-28 14:14:39 -04002019 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002020 if (e->is<GlobalVarDeclaration>()) {
2021 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002022 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002023 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2024 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002025 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002026 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002027 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002028 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002029
2030 int location = var.modifiers().fLayout.fLocation;
2031 if (location < 0) {
2032 fErrors.error(var.fOffset,
2033 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002034 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002035 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002036 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002037 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002038 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002039 if (colorIndex) {
2040 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002041 }
Brian Osmanc0213602020-10-06 14:43:32 -04002042 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002043 }
2044 this->write(";\n");
2045 }
2046 }
Timothy Liang7d637782018-06-05 09:58:07 -04002047 }
John Stiles270cec22021-02-17 12:59:36 -05002048 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002049 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002050 }
2051 this->write("};\n");
2052}
2053
2054void MetalCodeGenerator::writeInterfaceBlocks() {
2055 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002056 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002057 if (e->is<InterfaceBlock>()) {
2058 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002059 wroteInterfaceBlock = true;
2060 }
2061 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002062 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002063 this->writeLine("struct sksl_synthetic_uniforms {");
2064 this->writeLine(" float u_skRTHeight;");
2065 this->writeLine("};");
2066 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002067}
2068
John Stilesdc75a972020-11-25 16:24:55 -05002069void MetalCodeGenerator::writeStructDefinitions() {
2070 for (const ProgramElement* e : fProgram.elements()) {
2071 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002072 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002073 }
2074 }
2075}
2076
John Stilescdcdb042020-07-06 09:03:51 -04002077void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2078 // Visit the interface blocks.
2079 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002080 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002081 }
Brian Osman133724c2020-10-28 14:14:39 -04002082 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002083 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002084 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002085 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002086 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2087 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2088 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002089 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002090 var.type().typeKind() == Type::TypeKind::kSampler) {
2091 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2092 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002093 visitor->visitTexture(var.type(), var.name());
2094 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002095 } else {
2096 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002097 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002098 }
2099 }
2100 }
John Stilescdcdb042020-07-06 09:03:51 -04002101}
2102
2103void MetalCodeGenerator::writeGlobalStruct() {
2104 class : public GlobalStructVisitor {
2105 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002106 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002107 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002108 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002109 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002110 fCodeGen->write("* ");
2111 fCodeGen->writeName(blockName);
2112 fCodeGen->write(";\n");
2113 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002114 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002115 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002116 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002117 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002118 fCodeGen->write(" ");
2119 fCodeGen->writeName(name);
2120 fCodeGen->write(";\n");
2121 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002122 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002123 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002124 fCodeGen->write(" sampler ");
2125 fCodeGen->writeName(name);
2126 fCodeGen->write(";\n");
2127 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002128 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002129 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002130 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002131 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002132 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002133 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002134 fCodeGen->write(";\n");
2135 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002136 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002137 if (fFirst) {
2138 fCodeGen->write("struct Globals {\n");
2139 fFirst = false;
2140 }
2141 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002142 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002143 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002144 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002145 fFirst = true;
2146 }
2147 }
2148
2149 MetalCodeGenerator* fCodeGen = nullptr;
2150 bool fFirst = true;
2151 } visitor;
2152
2153 visitor.fCodeGen = this;
2154 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002155 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002156}
2157
2158void MetalCodeGenerator::writeGlobalInit() {
2159 class : public GlobalStructVisitor {
2160 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002161 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002162 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002163 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002164 fCodeGen->write("&");
2165 fCodeGen->writeName(blockName);
2166 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002167 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002168 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002169 fCodeGen->writeName(name);
2170 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002171 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002172 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002173 fCodeGen->writeName(name);
2174 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002175 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002176 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002177 if (value) {
2178 fCodeGen->writeVarInitializer(var, *value);
2179 } else {
2180 fCodeGen->write("{}");
2181 }
2182 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002183 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002184 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002185 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002186 fFirst = false;
2187 } else {
2188 fCodeGen->write(", ");
2189 }
2190 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002191 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002192 if (!fFirst) {
2193 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002194 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002195 }
2196 }
2197 MetalCodeGenerator* fCodeGen = nullptr;
2198 bool fFirst = true;
2199 } visitor;
2200
2201 visitor.fCodeGen = this;
2202 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002203 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002204}
2205
Ethan Nicholascc305772017-10-13 16:17:45 -04002206void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002207 switch (e.kind()) {
2208 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002209 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002210 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002211 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2212 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2213 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002214 if (-1 == builtin) {
2215 // normal var
2216 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002217 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002218 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2219 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002220 }
2221 break;
2222 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002223 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002224 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002225 break;
John Stilesdc75a972020-11-25 16:24:55 -05002226 case ProgramElement::Kind::kStructDefinition:
2227 // Handled in writeStructDefinitions. Do nothing.
2228 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002229 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002230 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002231 break;
John Stiles569249b2020-11-03 12:18:22 -05002232 case ProgramElement::Kind::kFunctionPrototype:
2233 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2234 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002235 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002236 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2237 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002238 this->writeLine(";");
2239 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002240 case ProgramElement::Kind::kEnum:
2241 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002242 default:
John Stileseada7bc2021-02-02 16:29:32 -05002243 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002244 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002245 }
2246}
2247
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002248MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2249 if (!e) {
2250 return kNo_Requirements;
2251 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002252 switch (e->kind()) {
2253 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002254 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002255 Requirements result = this->requirements(f.function());
2256 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002257 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002258 }
2259 return result;
2260 }
John Stiles7384b372021-04-01 13:48:15 -04002261 case Expression::Kind::kConstructor:
2262 case Expression::Kind::kConstructorArray:
2263 case Expression::Kind::kConstructorDiagonalMatrix: {
2264 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002265 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002266 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002267 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002268 }
2269 return result;
2270 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002271 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002272 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002273 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002274 return kGlobals_Requirement;
2275 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002276 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002277 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002278 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002279 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002280 case Expression::Kind::kBinary: {
2281 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002282 return this->requirements(bin.left().get()) |
2283 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002284 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002285 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002286 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002287 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002288 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002289 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002290 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002291 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002292 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002293 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002294 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002295 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2296 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002297 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002298 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002299 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002300 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002301 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002302 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002303 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002304 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002305 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002306 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002307 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002308 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002309 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002310 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002311 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002312 } else {
2313 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002314 }
2315 }
2316 return result;
2317 }
2318 default:
2319 return kNo_Requirements;
2320 }
2321}
2322
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002323MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2324 if (!s) {
2325 return kNo_Requirements;
2326 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002327 switch (s->kind()) {
2328 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002329 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002330 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002331 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002332 }
2333 return result;
2334 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002335 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002336 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002337 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002338 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002339 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002340 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002341 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002342 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002343 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002344 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002345 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002346 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002347 return this->requirements(i.test().get()) |
2348 this->requirements(i.ifTrue().get()) |
2349 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002350 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002351 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002352 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002353 return this->requirements(f.initializer().get()) |
2354 this->requirements(f.test().get()) |
2355 this->requirements(f.next().get()) |
2356 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002357 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002358 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002359 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002360 return this->requirements(d.test().get()) |
2361 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002362 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002363 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002364 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002365 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002366 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2367 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002368 }
2369 return result;
2370 }
2371 default:
2372 return kNo_Requirements;
2373 }
2374}
2375
2376MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002377 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002378 return kNo_Requirements;
2379 }
2380 auto found = fRequirements.find(&f);
2381 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002382 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002383 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002384 if (e->is<FunctionDefinition>()) {
2385 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002386 if (&def.declaration() == &f) {
2387 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002388 fRequirements[&f] = reqs;
2389 return reqs;
2390 }
2391 }
2392 }
John Stiles569249b2020-11-03 12:18:22 -05002393 // We never found a definition for this declared function, but it's legal to prototype a
2394 // function without ever giving a definition, as long as you don't call it.
2395 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002396 }
2397 return found->second;
2398}
2399
Timothy Liangb8eeb802018-07-23 16:46:16 -04002400bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002401 StringStream header;
2402 {
2403 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002404 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002405 this->writeStructDefinitions();
2406 this->writeUniformStruct();
2407 this->writeInputStruct();
2408 this->writeOutputStruct();
2409 this->writeInterfaceBlocks();
2410 this->writeGlobalStruct();
2411 }
2412 StringStream body;
2413 {
2414 AutoOutputStream outputToBody(this, &body, &fIndentation);
2415 for (const ProgramElement* e : fProgram.elements()) {
2416 this->writeProgramElement(*e);
2417 }
2418 }
2419 write_stringstream(header, *fOut);
2420 write_stringstream(fExtraFunctions, *fOut);
2421 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002422 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002423}
2424
John Stilesa6841be2020-08-06 14:11:56 -04002425} // namespace SkSL