blob: cb6b81e0dfdf8c39d1fc6c030664fa27ce94e5ad [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
John Stiles7384b372021-04-01 13:48:15 -040013#include "src/sksl/ir/SkSLConstructorArray.h"
John Stiles8cad6372021-04-07 12:31:13 -040014#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stiles7384b372021-04-01 13:48:15 -040015#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040016#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040017#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040018#include "src/sksl/ir/SkSLConstructorStruct.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLExpressionStatement.h"
20#include "src/sksl/ir/SkSLExtension.h"
21#include "src/sksl/ir/SkSLIndexExpression.h"
22#include "src/sksl/ir/SkSLModifiersDeclaration.h"
23#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050024#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040026
Brian Osmanc262a122020-08-06 16:34:34 -040027#include <algorithm>
28
Ethan Nicholascc305772017-10-13 16:17:45 -040029namespace SkSL {
30
John Stiles45990502021-02-16 10:55:27 -050031const char* MetalCodeGenerator::OperatorName(Operator op) {
32 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050033 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050034 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050035 }
36}
37
John Stilescdcdb042020-07-06 09:03:51 -040038class MetalCodeGenerator::GlobalStructVisitor {
39public:
40 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050041 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
42 virtual void visitTexture(const Type& type, const String& name) = 0;
43 virtual void visitSampler(const Type& type, const String& name) = 0;
44 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040045};
46
Timothy Liangee84fe12018-05-18 14:38:19 -040047void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050048 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
49 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
50 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
51 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
52 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
53 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
54 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
55 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
56 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
57 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
58 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
59 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
60 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
61 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
62 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
63 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
64 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
65 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
66 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
67 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
68 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
69 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
70 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
71 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
72 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
73 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
74 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
75 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
76 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050077 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050078 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040079}
80
Ethan Nicholascc305772017-10-13 16:17:45 -040081void MetalCodeGenerator::write(const char* s) {
82 if (!s[0]) {
83 return;
84 }
85 if (fAtLineStart) {
86 for (int i = 0; i < fIndentation; i++) {
87 fOut->writeText(" ");
88 }
89 }
90 fOut->writeText(s);
91 fAtLineStart = false;
92}
93
94void MetalCodeGenerator::writeLine(const char* s) {
95 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050096 this->writeLine();
Ethan Nicholascc305772017-10-13 16:17:45 -040097}
98
99void MetalCodeGenerator::write(const String& s) {
100 this->write(s.c_str());
101}
102
103void MetalCodeGenerator::writeLine(const String& s) {
104 this->writeLine(s.c_str());
105}
106
107void MetalCodeGenerator::writeLine() {
John Stilese8b5a732021-03-12 13:25:52 -0500108 fOut->writeText(fLineEnding);
109 fAtLineStart = true;
110}
111
112void MetalCodeGenerator::finishLine() {
113 if (!fAtLineStart) {
114 this->writeLine();
115 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400116}
117
118void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400119 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400120}
121
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500122String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400123 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500124 case Type::TypeKind::kArray:
125 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
126 return String::printf("array<%s, %d>",
127 this->typeName(type.componentType()).c_str(), type.columns());
128
Ethan Nicholase6592142020-09-08 10:22:09 -0400129 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500130 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500131
Ethan Nicholase6592142020-09-08 10:22:09 -0400132 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500133 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
134 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500135
Ethan Nicholase6592142020-09-08 10:22:09 -0400136 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500137 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500138
John Stilesfd41d872020-11-25 22:39:45 -0500139 case Type::TypeKind::kEnum:
140 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500141
Ethan Nicholascc305772017-10-13 16:17:45 -0400142 default:
John Stiles54e7c052021-01-11 14:22:36 -0500143 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400144 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500145 return fContext.fTypes.fFloat->name();
146 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500147 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500148 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500149 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400150 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500151 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400152 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400153 }
154}
155
Brian Osman02bc5222021-01-28 11:00:20 -0500156void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
157 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500158 this->writeLine("struct " + type.name() + " {");
159 fIndentation++;
160 this->writeFields(type.fields(), type.fOffset);
161 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500162 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500163}
164
John Stilesb4418502021-02-04 10:57:08 -0500165void MetalCodeGenerator::writeType(const Type& type) {
166 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500167}
168
Ethan Nicholascc305772017-10-13 16:17:45 -0400169void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 switch (expr.kind()) {
171 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400172 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400173 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400174 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400175 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400176 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400177 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400178 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400179 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
180 break;
John Stiles8cad6372021-04-07 12:31:13 -0400181 case Expression::Kind::kConstructorCompound:
182 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400183 break;
184 case Expression::Kind::kConstructorDiagonalMatrix:
185 case Expression::Kind::kConstructorSplat:
186 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400187 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400188 case Expression::Kind::kConstructorMatrixResize:
189 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
190 parentPrecedence);
191 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400192 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400193 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400194 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400195 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400196 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400197 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400198 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400199 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400200 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400201 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400202 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400203 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400204 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400205 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400206 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400207 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400208 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400209 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400210 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400211 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400212 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400213 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400214 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400215 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400216 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400217 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400218 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400219 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400220 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400221 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400222 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400223 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400224 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400225 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400226 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400227 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400228 break;
229 default:
John Stileseada7bc2021-02-02 16:29:32 -0500230 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500231 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400232 }
233}
234
John Stiles06b84ef2020-12-09 12:35:48 -0500235String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
236 const ExpressionArray& arguments,
237 const SkTArray<VariableReference*>& outVars) {
238 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
239 const FunctionDeclaration& function = call.function();
240
John Stilese1068342021-03-22 11:57:41 -0400241 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
242 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500243 const char* separator = "";
244
245 // Emit a prototype for the function we'll be calling through to in our helper.
246 if (!function.isBuiltin()) {
247 this->writeFunctionDeclaration(function);
248 this->writeLine(";");
249 }
250
251 // Synthesize a helper function that takes the same inputs as `function`, except in places where
252 // `outVars` is non-null; in those places, we take the type of the VariableReference.
253 //
254 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500255 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500256 this->write(" ");
257 this->write(name);
258 this->write("(");
259 this->writeFunctionRequirementParams(function, separator);
260
261 SkASSERT(outVars.size() == arguments.size());
262 SkASSERT(outVars.size() == function.parameters().size());
263
John Stiles73e2c892021-02-13 13:58:01 -0500264 // We need to detect cases where the caller passes the same variable as an out-param more than
265 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
266 // redundant input parameter entirely, and not give it any name.)
267 std::unordered_set<const Variable*> writtenVars;
268
John Stiles06b84ef2020-12-09 12:35:48 -0500269 for (int index = 0; index < arguments.count(); ++index) {
270 this->write(separator);
271 separator = ", ";
272
273 const Variable* param = function.parameters()[index];
274 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
275
276 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500277 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500278
279 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
280 this->write("&");
281 }
282 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500283 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
284 if (didInsert) {
285 this->write(" ");
286 fIgnoreVariableReferenceModifiers = true;
287 this->writeVariableReference(*outVars[index]);
288 fIgnoreVariableReferenceModifiers = false;
289 }
John Stiles06b84ef2020-12-09 12:35:48 -0500290 } else {
291 this->write(" _var");
292 this->write(to_string(index));
293 }
John Stiles06b84ef2020-12-09 12:35:48 -0500294 }
295 this->writeLine(") {");
296
297 ++fIndentation;
298 for (int index = 0; index < outVars.count(); ++index) {
299 if (!outVars[index]) {
300 continue;
301 }
302 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500303 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500304 this->write(" _var");
305 this->write(to_string(index));
306
307 const Variable* param = function.parameters()[index];
308 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
309 this->write(" = ");
310 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500311 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500312 fIgnoreVariableReferenceModifiers = false;
313 }
314
315 this->writeLine(";");
316 }
317
John Stilesf7410bd2021-01-19 13:07:55 -0500318 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500319 bool hasResult = (call.type().name() != "void");
320 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500321 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500322 this->write(" _skResult = ");
323 }
324
John Stilese1068342021-03-22 11:57:41 -0400325 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500326 this->write("(");
327 separator = "";
328 this->writeFunctionRequirementArgs(function, separator);
329
330 for (int index = 0; index < arguments.count(); ++index) {
331 this->write(separator);
332 separator = ", ";
333
334 this->write("_var");
335 this->write(to_string(index));
336 }
337 this->writeLine(");");
338
339 for (int index = 0; index < outVars.count(); ++index) {
340 if (!outVars[index]) {
341 continue;
342 }
343 // outParam.zyx = _var2;
344 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500345 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500346 fIgnoreVariableReferenceModifiers = false;
347 this->write(" = _var");
348 this->write(to_string(index));
349 this->writeLine(";");
350 }
351
352 if (hasResult) {
353 this->writeLine("return _skResult;");
354 }
355
356 --fIndentation;
357 this->writeLine("}");
358
359 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500360}
361
John Stilesf64e4072020-12-10 10:34:27 -0500362String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
363 return "as_type<" + outType.displayName() + ">";
364}
365
Ethan Nicholascc305772017-10-13 16:17:45 -0400366void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400367 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500368 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
369 // special handling.
370 if (function.isBuiltin() && !function.definition()) {
371 auto iter = fIntrinsicMap.find(function.name());
372 if (iter != fIntrinsicMap.end()) {
373 this->writeIntrinsicCall(c, iter->second);
374 return;
375 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400376 }
John Stilesb21fac22020-12-04 15:36:49 -0500377
John Stilesd7199b22020-12-30 16:22:58 -0500378 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
379 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
380 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
381 // allow a swizzle to be passed to a `floatN&`.)
382 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500383 const std::vector<const Variable*>& parameters = function.parameters();
384 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500385
386 bool foundOutParam = false;
387 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500388 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500389
390 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500391 // If this is an out parameter...
392 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500393 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500394 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500395 // Assignability was verified at IRGeneration time, so this should always succeed.
396 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
397 outVars[index] = info.fAssignedVar;
398 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500399 }
400 }
401
John Stiles06b84ef2020-12-09 12:35:48 -0500402 if (foundOutParam) {
403 // Out parameters need to be written back to at the end of the function. To do this, we
404 // synthesize a helper function which evaluates the out-param expression into a temporary
405 // variable, calls the original function, then writes the temp var back into the out param
406 // using the original out-param expression. (This lets us support things like swizzles and
407 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500408 this->write(getOutParamHelper(c, arguments, outVars));
409 } else {
John Stilese1068342021-03-22 11:57:41 -0400410 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500411 }
412
Ethan Nicholascc305772017-10-13 16:17:45 -0400413 this->write("(");
414 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500415 this->writeFunctionRequirementArgs(function, separator);
416 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400417 this->write(separator);
418 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500419
420 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500421 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500422 } else {
Brian Osman00185012021-02-04 16:07:11 -0500423 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500424 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400425 }
426 this->write(")");
427}
428
Brian Osman964f0a02020-12-29 10:15:22 -0500429static constexpr char kInverse2x2[] = R"(
430float2x2 float2x2_inverse(float2x2 m) {
431 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
432}
433)";
434
435static constexpr char kInverse3x3[] = R"(
436float3x3 float3x3_inverse(float3x3 m) {
437 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
438 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
439 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
440 float b01 = a22*a11 - a12*a21;
441 float b11 = -a22*a10 + a12*a20;
442 float b21 = a21*a10 - a11*a20;
443 float det = a00*b01 + a01*b11 + a02*b21;
444 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
445 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
446 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
447}
448)";
449
450static constexpr char kInverse4x4[] = R"(
451float4x4 float4x4_inverse(float4x4 m) {
452 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
453 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
454 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
455 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
456 float b00 = a00*a11 - a01*a10;
457 float b01 = a00*a12 - a02*a10;
458 float b02 = a00*a13 - a03*a10;
459 float b03 = a01*a12 - a02*a11;
460 float b04 = a01*a13 - a03*a11;
461 float b05 = a02*a13 - a03*a12;
462 float b06 = a20*a31 - a21*a30;
463 float b07 = a20*a32 - a22*a30;
464 float b08 = a20*a33 - a23*a30;
465 float b09 = a21*a32 - a22*a31;
466 float b10 = a21*a33 - a23*a31;
467 float b11 = a22*a33 - a23*a32;
468 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
469 return float4x4(a11*b11 - a12*b10 + a13*b09,
470 a02*b10 - a01*b11 - a03*b09,
471 a31*b05 - a32*b04 + a33*b03,
472 a22*b04 - a21*b05 - a23*b03,
473 a12*b08 - a10*b11 - a13*b07,
474 a00*b11 - a02*b08 + a03*b07,
475 a32*b02 - a30*b05 - a33*b01,
476 a20*b05 - a22*b02 + a23*b01,
477 a10*b10 - a11*b08 + a13*b06,
478 a01*b08 - a00*b10 - a03*b06,
479 a30*b04 - a31*b02 + a33*b00,
480 a21*b02 - a20*b04 - a23*b00,
481 a11*b07 - a10*b09 - a12*b06,
482 a00*b09 - a01*b07 + a02*b06,
483 a31*b01 - a30*b03 - a32*b00,
484 a20*b03 - a21*b01 + a22*b00) * (1/det);
485}
486)";
487
John Stilesd7199b22020-12-30 16:22:58 -0500488String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
489 // Only use polyfills for a function taking a single-argument square matrix.
490 if (arguments.size() == 1) {
491 const Type& type = arguments.front()->type();
492 if (type.isMatrix() && type.rows() == type.columns()) {
493 // Inject the correct polyfill based on the matrix size.
494 String name = this->typeName(type) + "_inverse";
495 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
496 if (didInsert) {
497 switch (type.rows()) {
498 case 2:
499 fExtraFunctions.writeText(kInverse2x2);
500 break;
501 case 3:
502 fExtraFunctions.writeText(kInverse3x3);
503 break;
504 case 4:
505 fExtraFunctions.writeText(kInverse4x4);
506 break;
507 }
508 }
509 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500510 }
511 }
John Stilesd7199b22020-12-30 16:22:58 -0500512 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
513 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500514}
515
Brian Osman93aed9a2020-12-28 15:18:46 -0500516static constexpr char kMatrixCompMult[] = R"(
517template <int C, int R>
518matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
519 matrix<float, C, R> result;
520 for (int c = 0; c < C; ++c) {
521 result[c] = a[c] * b[c];
522 }
523 return result;
524}
525)";
526
527void MetalCodeGenerator::writeMatrixCompMult() {
528 String name = "matrixCompMult";
529 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
530 fWrittenIntrinsics.insert(name);
531 fExtraFunctions.writeText(kMatrixCompMult);
532 }
533}
534
John Stiles86424eb2020-12-11 11:17:14 -0500535String MetalCodeGenerator::getTempVariable(const Type& type) {
536 String tempVar = "_skTemp" + to_string(fVarCount++);
537 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
538 return tempVar;
539}
540
John Stiles791c27d2020-12-30 14:56:57 -0500541void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
542 // Write out an intrinsic function call exactly as-is. No muss no fuss.
543 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500544 this->writeArgumentList(c.arguments());
545}
546
547void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500548 this->write("(");
549 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500550 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500551 this->write(separator);
552 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500553 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500554 }
555 this->write(")");
556}
557
John Stilesd7199b22020-12-30 16:22:58 -0500558void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400559 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400560 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500561 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500562 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400563 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500564 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400565 this->write(SAMPLER_SUFFIX);
566 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400567 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400568 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500569 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500570 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500571 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500572 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500573 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400574 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400575 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500576 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400577 this->write(")");
578 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400579 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400580 }
John Stilesd7199b22020-12-30 16:22:58 -0500581 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400582 // 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 -0500583 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500584 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500585 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500586 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500587 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500588 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500589 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400590 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500591 }
Brian Osman46787d52020-11-24 14:18:23 -0500592 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500593 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500594 if (arguments[0]->type().columns() == 1) {
595 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500596 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500597 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500598 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500599 this->write(")");
600 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500601 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500602 }
603 break;
604 }
John Stilesd7199b22020-12-30 16:22:58 -0500605 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500606 if (arguments[0]->type().columns() == 1) {
607 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500608 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500609 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500610 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500611 this->write(")");
612 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500613 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500614 }
615 break;
616 }
John Stilesd7199b22020-12-30 16:22:58 -0500617 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500618 if (arguments[0]->type().columns() == 1) {
619 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
620 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500621 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500622 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500623 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500624 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500625 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500626 this->write("))");
627 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500628 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500629 }
630 break;
631 }
John Stilesd7199b22020-12-30 16:22:58 -0500632 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500633 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500634 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500635 this->write(")");
636 break;
637 }
John Stilesd7199b22020-12-30 16:22:58 -0500638 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500639 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500640 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500641 this->write(")");
642 break;
643 }
John Stilesd7199b22020-12-30 16:22:58 -0500644 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500645 this->write(this->getBitcastIntrinsic(c.type()));
646 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500647 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500648 this->write(")");
649 break;
650 }
John Stilesd7199b22020-12-30 16:22:58 -0500651 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500652 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500653 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500654 this->write(") * 57.2957795)");
655 break;
656 }
John Stilesd7199b22020-12-30 16:22:58 -0500657 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500658 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500659 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500660 this->write(") * 0.0174532925)");
661 break;
662 }
John Stilesd7199b22020-12-30 16:22:58 -0500663 case kDFdx_IntrinsicKind: {
664 this->write("dfdx");
665 this->writeArgumentList(c.arguments());
666 break;
667 }
668 case kDFdy_IntrinsicKind: {
669 // Flipping Y also negates the Y derivatives.
John Stiles270cec22021-02-17 12:59:36 -0500670 if (fProgram.fConfig->fSettings.fFlipY) {
John Stilesd7199b22020-12-30 16:22:58 -0500671 this->write("-");
672 }
673 this->write("dfdy");
674 this->writeArgumentList(c.arguments());
675 break;
676 }
677 case kInverse_IntrinsicKind: {
678 this->write(this->getInversePolyfill(arguments));
679 this->writeArgumentList(c.arguments());
680 break;
681 }
682 case kInversesqrt_IntrinsicKind: {
683 this->write("rsqrt");
684 this->writeArgumentList(c.arguments());
685 break;
686 }
687 case kAtan_IntrinsicKind: {
688 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
689 this->writeArgumentList(c.arguments());
690 break;
691 }
692 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500693 if (arguments[0]->type().columns() == 1) {
694 // We need to synthesize `I - 2 * N * I * N`.
695 String tmpI = this->getTempVariable(arguments[0]->type());
696 String tmpN = this->getTempVariable(arguments[1]->type());
697
698 // (_skTempI = ...
699 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500700 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500701
702 // , _skTempN = ...
703 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500704 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500705
706 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
707 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
708 } else {
709 this->writeSimpleIntrinsic(c);
710 }
711 break;
712 }
John Stilesd7199b22020-12-30 16:22:58 -0500713 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500714 if (arguments[0]->type().columns() == 1) {
715 // Metal does implement refract for vectors; rather than reimplementing refract from
716 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
717 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500718 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500719 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500720 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500721 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500722 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500723 this->write(").x)");
724 } else {
725 this->writeSimpleIntrinsic(c);
726 }
727 break;
728 }
John Stiles23456532020-12-30 18:12:48 -0500729 case kRoundEven_IntrinsicKind: {
730 this->write("rint");
731 this->writeArgumentList(c.arguments());
732 break;
733 }
John Stilesd7199b22020-12-30 16:22:58 -0500734 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500735 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500736 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500737 this->write(")");
738 break;
739 }
John Stilesd7199b22020-12-30 16:22:58 -0500740 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500741 // Create a temp variable to store the expression, to avoid double-evaluating it.
742 String skTemp = this->getTempVariable(arguments[0]->type());
743 String exprType = this->typeName(arguments[0]->type());
744
745 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
746 // Use select to detect zero inputs and force a -1 result.
747
748 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
749 this->write("(");
750 this->write(skTemp);
751 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500752 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500753 this->write("), select(ctz(");
754 this->write(skTemp);
755 this->write("), ");
756 this->write(exprType);
757 this->write("(-1), ");
758 this->write(skTemp);
759 this->write(" == ");
760 this->write(exprType);
761 this->write("(0)))");
762 break;
763 }
John Stilesd7199b22020-12-30 16:22:58 -0500764 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500765 // Create a temp variable to store the expression, to avoid double-evaluating it.
766 String skTemp1 = this->getTempVariable(arguments[0]->type());
767 String exprType = this->typeName(arguments[0]->type());
768
769 // GLSL findMSB is actually quite different from Metal's clz:
770 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
771 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
772
773 // (_skTemp1 = (.....),
774 this->write("(");
775 this->write(skTemp1);
776 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500777 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500778 this->write("), ");
779
780 // Signed input types might be negative; we need another helper variable to negate the
781 // input (since we can only find one bits, not zero bits).
782 String skTemp2;
783 if (arguments[0]->type().isSigned()) {
784 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
785 skTemp2 = this->getTempVariable(arguments[0]->type());
786 this->write(skTemp2);
787 this->write(" = (select(");
788 this->write(skTemp1);
789 this->write(", ~");
790 this->write(skTemp1);
791 this->write(", ");
792 this->write(skTemp1);
793 this->write(" < 0)), ");
794 } else {
795 skTemp2 = skTemp1;
796 }
797
798 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
799 this->write("select(");
800 this->write(this->typeName(c.type()));
801 this->write("(clz(");
802 this->write(skTemp2);
803 this->write(")), ");
804 this->write(this->typeName(c.type()));
805 this->write("(-1), ");
806 this->write(skTemp2);
807 this->write(" == ");
808 this->write(exprType);
809 this->write("(0)))");
810 break;
811 }
John Stilesd7199b22020-12-30 16:22:58 -0500812 case kMatrixCompMult_IntrinsicKind: {
813 this->writeMatrixCompMult();
814 this->writeSimpleIntrinsic(c);
815 break;
816 }
817 case kCompareEqual_IntrinsicKind:
818 case kCompareGreaterThan_IntrinsicKind:
819 case kCompareGreaterThanEqual_IntrinsicKind:
820 case kCompareLessThan_IntrinsicKind:
821 case kCompareLessThanEqual_IntrinsicKind:
822 case kCompareNotEqual_IntrinsicKind: {
823 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500824 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500825 switch (kind) {
826 case kCompareEqual_IntrinsicKind:
827 this->write(" == ");
828 break;
829 case kCompareNotEqual_IntrinsicKind:
830 this->write(" != ");
831 break;
832 case kCompareLessThan_IntrinsicKind:
833 this->write(" < ");
834 break;
835 case kCompareLessThanEqual_IntrinsicKind:
836 this->write(" <= ");
837 break;
838 case kCompareGreaterThan_IntrinsicKind:
839 this->write(" > ");
840 break;
841 case kCompareGreaterThanEqual_IntrinsicKind:
842 this->write(" >= ");
843 break;
844 default:
John Stilesf57207b2021-02-02 17:50:34 -0500845 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500846 }
Brian Osman00185012021-02-04 16:07:11 -0500847 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500848 this->write(")");
849 break;
850 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400851 default:
John Stilesf57207b2021-02-02 17:50:34 -0500852 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400853 }
854}
855
John Stilesfcf8cb22020-08-06 14:29:22 -0400856// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
857// Cells that don't exist in the source matrix will be populated with identity-matrix values.
858void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
859 SkASSERT(rows <= 4);
860 SkASSERT(columns <= 4);
861
862 const char* columnSeparator = "";
863 for (int c = 0; c < columns; ++c) {
864 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
865 columnSeparator = "), ";
866
867 // Determine how many values to take from the source matrix for this row.
868 int swizzleLength = 0;
869 if (c < sourceMatrix.columns()) {
870 swizzleLength = std::min<>(rows, sourceMatrix.rows());
871 }
872
873 // Emit all the values from the source matrix row.
874 bool firstItem;
875 switch (swizzleLength) {
876 case 0: firstItem = true; break;
877 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
878 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
879 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
880 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
881 default: SkUNREACHABLE;
882 }
883
884 // Emit the placeholder identity-matrix cells.
885 for (int r = swizzleLength; r < rows; ++r) {
886 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
887 firstItem = false;
888 }
889 }
890
891 fExtraFunctions.writeText(")");
892}
893
894// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
895// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400896void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles8e3b6be2020-10-13 11:14:08 -0400897 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400898 size_t argIndex = 0;
899 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400900 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400901
902 const char* columnSeparator = "";
903 for (int c = 0; c < columns; ++c) {
904 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
905 columnSeparator = "), ";
906
907 const char* rowSeparator = "";
908 for (int r = 0; r < rows; ++r) {
909 fExtraFunctions.writeText(rowSeparator);
910 rowSeparator = ", ";
911
912 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400913 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400914 switch (argType.typeKind()) {
915 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400916 fExtraFunctions.printf("x%zu", argIndex);
917 break;
918 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400919 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400920 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
921 break;
922 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400923 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400924 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
925 argPosition / argType.rows(),
926 argPosition % argType.rows());
927 break;
928 }
929 default: {
930 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
931 fExtraFunctions.writeText("<error>");
932 break;
933 }
934 }
935
936 ++argPosition;
937 if (argPosition >= argType.columns() * argType.rows()) {
938 ++argIndex;
939 argPosition = 0;
940 }
941 } else {
942 SkDEBUGFAIL("not enough arguments for matrix constructor");
943 fExtraFunctions.writeText("<error>");
944 }
945 }
946 }
947
948 if (argPosition != 0 || argIndex != args.size()) {
949 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
950 fExtraFunctions.writeText(", <error>");
951 }
952
953 fExtraFunctions.writeText(")");
954}
955
John Stiles1bdafbf2020-05-28 12:17:20 -0400956// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
957// Keeps track of previously generated constructors so that we won't generate more than one
958// constructor for any given permutation of input argument types. Returns the name of the
959// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400960String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400961 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500962 int columns = matrix.columns();
963 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400964 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400965
966 // Create the helper-method name and use it as our lookup key.
967 String name;
968 name.appendf("float%dx%d_from", columns, rows);
969 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500970 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400971 }
972
973 // If a helper-method has already been synthesized, we don't need to synthesize it again.
974 auto [iter, newlyCreated] = fHelpers.insert(name);
975 if (!newlyCreated) {
976 return name;
977 }
978
979 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
980 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
981 // supply a mixture of scalars and vectors.)
982 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
983
984 size_t argIndex = 0;
985 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400986 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400987 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500988 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400989 argSeparator = ", ";
990 }
991
992 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
993
John Stiles9aeed132020-11-24 17:36:06 -0500994 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400995 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400996 } else {
John Stiles5abb9e12021-04-06 13:47:19 -0400997 this->assembleMatrixFromExpressions(c, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400998 }
999
John Stilesfcf8cb22020-08-06 14:29:22 -04001000 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001001 return name;
1002}
1003
1004bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
1005 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
1006 return false;
1007 }
1008 if (t1.columns() > 1) {
1009 return this->canCoerce(t1.componentType(), t2.componentType());
1010 }
Ethan Nicholase1f55022019-02-05 17:17:40 -05001011 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -05001012}
1013
John Stiles8cad6372021-04-07 12:31:13 -04001014bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001015 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -04001016
1017 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
1018 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
1019 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
1020 // scalars can be constructed trivially. In more complex cases, we generate a helper function
1021 // that converts our inputs into a properly-shaped matrix.
1022 // A matrix construct helper method is always used if any input argument is a matrix.
1023 // Helper methods are also necessary when any argument would span multiple rows. For instance:
1024 //
1025 // float2 x = (1, 2);
1026 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1027 // | 2 4 6 |
1028 //
1029 // float2 x = (2, 3);
1030 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1031 // | 2 4 6 |
1032 //
1033 // float4 x = (1, 2, 3, 4);
1034 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1035 // | 2 4 |
1036 //
1037
1038 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001039 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001040 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001041 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001042 return true;
1043 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001044 position += expr->type().columns();
1045 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001046 // An input argument would span multiple rows; a helper function is required.
1047 return true;
1048 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001049 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001050 // We've advanced to the end of a row. Wrap to the start of the next row.
1051 position = 0;
1052 }
1053 }
1054
1055 return false;
1056}
1057
John Stiles5abb9e12021-04-06 13:47:19 -04001058void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1059 Precedence parentPrecedence) {
1060 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1061 // matrix-construct helper here.
1062 this->write(this->getMatrixConstructHelper(c));
1063 this->write("(");
1064 this->writeExpression(*c.argument(), Precedence::kSequence);
1065 this->write(")");
1066}
1067
John Stiles8cad6372021-04-07 12:31:13 -04001068void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1069 Precedence parentPrecedence) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001070 if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001071 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001072 } else {
1073 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1074 }
1075}
John Stiles7384b372021-04-01 13:48:15 -04001076
John Stiles8cad6372021-04-07 12:31:13 -04001077void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1078 Precedence parentPrecedence) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001079 // Emit and invoke a matrix-constructor helper method if one is necessary.
1080 if (this->matrixConstructHelperIsNeeded(c)) {
1081 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001082 this->write("(");
1083 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001084 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001085 this->write(separator);
1086 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001087 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001088 }
John Stiles1fa15b12020-05-28 17:36:54 +00001089 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001090 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001091 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001092
John Stiles2bec8ab2021-04-06 18:40:04 -04001093 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1094 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1095 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1096 // can group our inputs up and synthesize a constructor for each column.
1097 const Type& matrixType = c.type();
1098 const Type& columnType = matrixType.componentType().toCompound(
1099 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1100
1101 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001102 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001103 const char* separator = "";
1104 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001105 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001106 this->write(separator);
1107 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001108 if (arg->type().columns() < matrixType.rows()) {
1109 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001110 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001111 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001112 this->write("(");
1113 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001114 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001115 }
Brian Osman00185012021-02-04 16:07:11 -05001116 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001117 if (scalarCount && scalarCount == matrixType.rows()) {
1118 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001119 this->write(")");
1120 scalarCount = 0;
1121 }
1122 }
John Stiles7384b372021-04-01 13:48:15 -04001123 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001124}
1125
John Stilesb14a8192021-04-05 11:40:46 -04001126void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1127 const char* leftBracket,
1128 const char* rightBracket,
1129 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001130 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001131 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001132 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001133 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001134 this->write(separator);
1135 separator = ", ";
1136 this->writeExpression(*arg, Precedence::kSequence);
1137 }
John Stilesb14a8192021-04-05 11:40:46 -04001138 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001139}
1140
John Stilesb14a8192021-04-05 11:40:46 -04001141void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1142 const char* leftBracket,
1143 const char* rightBracket,
1144 Precedence parentPrecedence) {
1145 // If the type is coercible, emit it directly without the cast.
1146 auto args = c.argumentSpan();
1147 if (args.size() == 1) {
1148 if (this->canCoerce(c.type(), args.front()->type())) {
1149 this->writeExpression(*args.front(), parentPrecedence);
1150 return;
1151 }
John Stilesfd7252f2021-04-04 22:24:40 -04001152 }
1153
John Stilesb14a8192021-04-05 11:40:46 -04001154 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001155}
1156
Ethan Nicholascc305772017-10-13 16:17:45 -04001157void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001158 if (fRTHeightName.length()) {
1159 this->write("float4(_fragCoord.x, ");
1160 this->write(fRTHeightName.c_str());
1161 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001162 } else {
1163 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1164 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001165}
1166
1167void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001168 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001169 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001170 // we're actually targeting the clones.
1171 if (fIgnoreVariableReferenceModifiers) {
1172 this->writeName(ref.variable()->name());
1173 return;
1174 }
1175
Ethan Nicholas78686922020-10-08 06:46:27 -04001176 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001177 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001178 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001179 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001180 case SK_FRAGCOORD_BUILTIN:
1181 this->writeFragCoord();
1182 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001183 case SK_VERTEXID_BUILTIN:
1184 this->write("sk_VertexID");
1185 break;
1186 case SK_INSTANCEID_BUILTIN:
1187 this->write("sk_InstanceID");
1188 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001189 case SK_CLOCKWISE_BUILTIN:
1190 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001191 // clockwise to match Skia convention.
John Stiles270cec22021-02-17 12:59:36 -05001192 this->write(fProgram.fConfig->fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001193 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001194 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001195 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001196 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001197 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001198 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001199 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001200 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001201 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1202 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001203 this->write("_uniforms.");
1204 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001205 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001206 }
1207 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001208 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001209 }
1210}
1211
1212void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001213 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001214 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001215 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001216 this->write("]");
1217}
1218
1219void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001220 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1221 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001222 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001223 this->write(".");
1224 }
Timothy Liang7d637782018-06-05 09:58:07 -04001225 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001226 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001227 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001228 break;
1229 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001230 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001231 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001232 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001233 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001234 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001235 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1236 this->write("->");
1237 }
Timothy Liang651286f2018-06-07 09:55:33 -04001238 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001239 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001240 }
1241}
1242
1243void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001244 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001246 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001247 SkASSERT(c >= 0 && c <= 3);
1248 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001249 }
1250}
1251
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001252void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1253 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001254 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001255
1256 auto [iter, wasInserted] = fHelpers.insert(key);
1257 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001258 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001259 " left = left * right;\n"
1260 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001261 "}\n",
1262 this->typeName(result).c_str(), this->typeName(left).c_str(),
1263 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001264 }
1265}
1266
John Stiles01cdf012021-02-10 09:53:41 -05001267void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1268 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1269 left.description().c_str(), right.description().c_str());
1270
1271 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1272
1273 auto [iter, wasInserted] = fHelpers.insert(key);
1274 if (wasInserted) {
1275 fExtraFunctions.printf(
1276 "thread bool operator==(const %s left, const %s right) {\n"
1277 " return",
1278 this->typeName(left).c_str(), this->typeName(right).c_str());
1279
1280 for (int index=0; index<left.columns(); ++index) {
1281 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1282 index == 0 ? "" : " &&", index, index);
1283 }
1284 fExtraFunctions.printf(";\n"
1285 "}\n");
1286 }
1287}
1288
1289void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1290 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1291 left.description().c_str(), right.description().c_str());
1292
1293 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1294
1295 auto [iter, wasInserted] = fHelpers.insert(key);
1296 if (wasInserted) {
1297 fExtraFunctions.printf(
1298 "thread bool operator!=(const %s left, const %s right) {\n"
1299 " return",
1300 this->typeName(left).c_str(), this->typeName(right).c_str());
1301
1302 for (int index=0; index<left.columns(); ++index) {
1303 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1304 index == 0 ? "" : " ||", index, index);
1305 }
1306 fExtraFunctions.printf(";\n"
1307 "}\n");
1308 }
1309}
1310
Ethan Nicholascc305772017-10-13 16:17:45 -04001311void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1312 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001313 const Expression& left = *b.left();
1314 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001315 const Type& leftType = left.type();
1316 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001317 Operator op = b.getOperator();
1318 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001319 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001320 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001321 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001322 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001323 this->write("all");
1324 needParens = true;
1325 }
1326 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001327 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001328 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001329 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001330 needParens = true;
1331 }
1332 break;
1333 default:
1334 break;
1335 }
1336 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001337 this->write("(");
1338 }
John Stiles01cdf012021-02-10 09:53:41 -05001339 if (leftType.isMatrix() && rightType.isMatrix()) {
John Stiles45990502021-02-16 10:55:27 -05001340 if (op.kind() == Token::Kind::TK_STAREQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001341 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
John Stiles45990502021-02-16 10:55:27 -05001342 } else if (op.kind() == Token::Kind::TK_EQEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001343 this->writeMatrixEqualityHelper(leftType, rightType);
John Stiles45990502021-02-16 10:55:27 -05001344 } else if (op.kind() == Token::Kind::TK_NEQ) {
John Stiles01cdf012021-02-10 09:53:41 -05001345 this->writeMatrixInequalityHelper(leftType, rightType);
1346 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001347 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001348 this->writeExpression(left, precedence);
John Stiles45990502021-02-16 10:55:27 -05001349 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001350 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001351 // This doesn't compile in Metal:
1352 // float4 x = float4(1);
1353 // x.xy *= float2x2(...);
1354 // with the error message "non-const reference cannot bind to vector element",
1355 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1356 // as long as the LHS has no side effects, and hope for the best otherwise.
1357 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001358 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001359 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001360 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001361 SkASSERT(opName.endsWith("="));
1362 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001363 this->write(" ");
1364 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001365 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001366 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001367 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001368 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001369 this->write(")");
1370 }
1371}
1372
1373void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1374 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001375 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001376 this->write("(");
1377 }
Brian Osman00185012021-02-04 16:07:11 -05001378 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001379 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001380 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001381 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001382 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1383 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001384 this->write(")");
1385 }
1386}
1387
1388void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1389 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001390 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001391 this->write("(");
1392 }
John Stilesd6449e92020-11-30 09:13:23 -05001393 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001394 this->writeExpression(*p.operand(), Precedence::kPrefix);
1395 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001396 this->write(")");
1397 }
1398}
1399
1400void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1401 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001402 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001403 this->write("(");
1404 }
Brian Osman00185012021-02-04 16:07:11 -05001405 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001406 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001407 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001408 this->write(")");
1409 }
1410}
1411
1412void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001413 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001414}
1415
1416void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001417 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001418 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001419 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001420 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001421 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001422 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001423 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001424 } else {
John Stiles12739df2020-12-29 09:47:20 -05001425 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001426 }
1427}
1428
1429void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001430 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001431}
1432
1433void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001434 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001435}
1436
John Stiles06b84ef2020-12-09 12:35:48 -05001437void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1438 const char*& separator) {
1439 Requirements requirements = this->requirements(f);
1440 if (requirements & kInputs_Requirement) {
1441 this->write(separator);
1442 this->write("_in");
1443 separator = ", ";
1444 }
1445 if (requirements & kOutputs_Requirement) {
1446 this->write(separator);
1447 this->write("_out");
1448 separator = ", ";
1449 }
1450 if (requirements & kUniforms_Requirement) {
1451 this->write(separator);
1452 this->write("_uniforms");
1453 separator = ", ";
1454 }
1455 if (requirements & kGlobals_Requirement) {
1456 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001457 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001458 separator = ", ";
1459 }
1460 if (requirements & kFragCoord_Requirement) {
1461 this->write(separator);
1462 this->write("_fragCoord");
1463 separator = ", ";
1464 }
1465}
1466
1467void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1468 const char*& separator) {
1469 Requirements requirements = this->requirements(f);
1470 if (requirements & kInputs_Requirement) {
1471 this->write(separator);
1472 this->write("Inputs _in");
1473 separator = ", ";
1474 }
1475 if (requirements & kOutputs_Requirement) {
1476 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001477 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001478 separator = ", ";
1479 }
1480 if (requirements & kUniforms_Requirement) {
1481 this->write(separator);
1482 this->write("Uniforms _uniforms");
1483 separator = ", ";
1484 }
1485 if (requirements & kGlobals_Requirement) {
1486 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001487 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001488 separator = ", ";
1489 }
1490 if (requirements & kFragCoord_Requirement) {
1491 this->write(separator);
1492 this->write("float4 _fragCoord");
1493 separator = ", ";
1494 }
1495}
1496
John Stilesda5cdf62021-01-28 11:47:29 -05001497int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1498 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001499 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001500}
1501
1502int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1503 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001504 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001505}
1506
John Stiles569249b2020-11-03 12:18:22 -05001507bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001508 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001509 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001510 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001511 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001512 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001513 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001514 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001515 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001516 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001517 break;
1518 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001519 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001520 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001521 }
1522 this->write("(Inputs _in [[stage_in]]");
1523 if (-1 != fUniformBuffer) {
1524 this->write(", constant Uniforms& _uniforms [[buffer(" +
1525 to_string(fUniformBuffer) + ")]]");
1526 }
Brian Osman133724c2020-10-28 14:14:39 -04001527 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001528 if (e->is<GlobalVarDeclaration>()) {
1529 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001530 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1531 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1532 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001533 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001534 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001535 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001536 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001537 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001538 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001539 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001540 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001541 }
1542 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001543 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001544 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001545 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001546 this->write(")]]");
1547 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001548 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001549 this->write(SAMPLER_SUFFIX);
1550 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001551 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001552 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001553 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001554 } else if (e->is<InterfaceBlock>()) {
1555 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001556 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001557 continue;
1558 }
1559 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001560 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001561 this->write("& " );
1562 this->write(fInterfaceBlockNameMap[&intf]);
1563 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001564 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001565 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001566 }
1567 }
John Stiles270cec22021-02-17 12:59:36 -05001568 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001569 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001570 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001571 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001572 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001573 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001574 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001575 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001576 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001577 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001578 separator = ", ";
1579 } else {
John Stilesb4418502021-02-04 10:57:08 -05001580 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001581 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001582 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001583 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001584 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001585 }
John Stiles569249b2020-11-03 12:18:22 -05001586 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001587 this->write(separator);
1588 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001589 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001590 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001591 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001592 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001593 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001594 }
Timothy Liang651286f2018-06-07 09:55:33 -04001595 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001596 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001597 }
John Stiles569249b2020-11-03 12:18:22 -05001598 this->write(")");
1599 return true;
1600}
Ethan Nicholascc305772017-10-13 16:17:45 -04001601
John Stiles569249b2020-11-03 12:18:22 -05001602void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1603 this->writeFunctionDeclaration(f.declaration());
1604 this->writeLine(";");
1605}
1606
John Stiles986c7fb2020-12-01 14:44:56 -05001607static bool is_block_ending_with_return(const Statement* stmt) {
1608 // This function detects (potentially nested) blocks that end in a return statement.
1609 if (!stmt->is<Block>()) {
1610 return false;
1611 }
1612 const StatementArray& block = stmt->as<Block>().children();
1613 for (int index = block.count(); index--; ) {
1614 const Statement& stmt = *block[index];
1615 if (stmt.is<ReturnStatement>()) {
1616 return true;
1617 }
1618 if (stmt.is<Block>()) {
1619 return is_block_ending_with_return(&stmt);
1620 }
1621 if (!stmt.is<Nop>()) {
1622 break;
1623 }
1624 }
1625 return false;
1626}
1627
John Stiles569249b2020-11-03 12:18:22 -05001628void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001629 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001630
John Stiles569249b2020-11-03 12:18:22 -05001631 if (!this->writeFunctionDeclaration(f.declaration())) {
1632 return;
1633 }
1634
John Stiles986c7fb2020-12-01 14:44:56 -05001635 fCurrentFunction = &f.declaration();
1636 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1637
John Stiles569249b2020-11-03 12:18:22 -05001638 this->writeLine(" {");
1639
John Stilese8da4d22021-03-24 09:19:45 -04001640 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001641 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001642 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001643 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001644 }
John Stilesc67b3622020-05-28 17:53:13 -04001645
Ethan Nicholascc305772017-10-13 16:17:45 -04001646 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001647 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001648 {
1649 AutoOutputStream outputToBuffer(this, &buffer);
1650 fIndentation++;
1651 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1652 if (!stmt->isEmpty()) {
1653 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001654 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001655 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001656 }
John Stilese8da4d22021-03-24 09:19:45 -04001657 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001658 // If the main function doesn't end with a return, we need to synthesize one here.
1659 if (!is_block_ending_with_return(f.body().get())) {
1660 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001661 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001662 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001663 }
John Stiles44532372020-12-07 12:33:55 -05001664 fIndentation--;
1665 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001666 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001667 this->write(fFunctionHeader);
1668 this->write(buffer.str());
1669}
1670
1671void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001672 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001673 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1674 this->write("thread ");
1675 }
1676 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001677 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 }
1679}
1680
1681void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001682 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001683 return;
1684 }
John Stiles06b84ef2020-12-09 12:35:48 -05001685 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001686 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001687 this->writeLine(intf.typeName() + " {");
1688 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001689 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001690 structType = &structType->componentType();
1691 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001692 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001693 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001694 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001695 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001696 }
1697 fIndentation--;
1698 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001699 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001700 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001701 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001702 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001703 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001704 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001705 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001706 } else if (intf.arraySize() == Type::kUnsizedArray){
1707 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001708 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001709 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001710 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001711 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001712 }
1713 this->writeLine(";");
1714}
1715
Timothy Liangdc89f192018-06-13 09:20:31 -04001716void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1717 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001718 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001719 int currentOffset = 0;
1720 for (const auto& field: fields) {
1721 int fieldOffset = field.fModifiers.fLayout.fOffset;
1722 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001723 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001724 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1725 return;
1726 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001727 if (fieldOffset != -1) {
1728 if (currentOffset > fieldOffset) {
1729 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001730 "offset of field '" + field.fName + "' must be at least " +
1731 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001732 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001733 } else if (currentOffset < fieldOffset) {
1734 this->write("char pad");
1735 this->write(to_string(fPaddingCount++));
1736 this->write("[");
1737 this->write(to_string(fieldOffset - currentOffset));
1738 this->writeLine("];");
1739 currentOffset = fieldOffset;
1740 }
1741 int alignment = memoryLayout.alignment(*fieldType);
1742 if (fieldOffset % alignment) {
1743 fErrors.error(parentOffset,
1744 "offset of field '" + field.fName + "' must be a multiple of " +
1745 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001746 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001747 }
1748 }
Brian Osman8609a242020-09-08 14:01:49 -04001749 size_t fieldSize = memoryLayout.size(*fieldType);
1750 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1751 fErrors.error(parentOffset, "field offset overflow");
1752 return;
1753 }
1754 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001755 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001756 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001757 this->write(" ");
1758 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001759 this->writeLine(";");
1760 if (parentIntf) {
1761 fInterfaceBlockMap[&field] = parentIntf;
1762 }
1763 }
1764}
1765
Ethan Nicholascc305772017-10-13 16:17:45 -04001766void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001767 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001768}
1769
Timothy Liang651286f2018-06-07 09:55:33 -04001770void MetalCodeGenerator::writeName(const String& name) {
1771 if (fReservedWords.find(name) != fReservedWords.end()) {
1772 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1773 }
1774 this->write(name);
1775}
1776
John Stilesb4418502021-02-04 10:57:08 -05001777void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1778 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001779 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001780 }
John Stilesb4418502021-02-04 10:57:08 -05001781 this->writeModifiers(varDecl.var().modifiers(), global);
1782 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001783 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001784 this->writeName(varDecl.var().name());
1785 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001786 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001787 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001788 }
1789 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001790}
1791
1792void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001793 switch (s.kind()) {
1794 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001795 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001796 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001797 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001798 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001799 this->write(";");
1800 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001801 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001802 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001803 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001804 case Statement::Kind::kVarDeclaration:
1805 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001806 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001807 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001808 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001809 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001810 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001811 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001813 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001814 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001815 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001816 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001817 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001818 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001819 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001820 this->write("break;");
1821 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001822 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001823 this->write("continue;");
1824 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001825 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001826 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001827 break;
John Stiles98c1f822020-09-09 14:18:53 -04001828 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001829 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001830 this->write(";");
1831 break;
1832 default:
John Stileseada7bc2021-02-02 16:29:32 -05001833 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001834 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001835 }
1836}
1837
Ethan Nicholascc305772017-10-13 16:17:45 -04001838void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001839 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1840 // something here to make the code valid).
1841 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001842 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001843 this->writeLine("{");
1844 fIndentation++;
1845 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001846 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1847 if (!stmt->isEmpty()) {
1848 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001849 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001850 }
1851 }
1852 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001853 fIndentation--;
1854 this->write("}");
1855 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001856}
1857
1858void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1859 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001860 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001861 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001862 this->writeStatement(*stmt.ifTrue());
1863 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001865 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001866 }
1867}
1868
1869void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001870 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1871 if (!f.initializer() && f.test() && !f.next()) {
1872 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001873 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001874 this->write(") ");
1875 this->writeStatement(*f.statement());
1876 return;
1877 }
1878
Ethan Nicholascc305772017-10-13 16:17:45 -04001879 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001880 if (f.initializer() && !f.initializer()->isEmpty()) {
1881 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001882 } else {
1883 this->write("; ");
1884 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001885 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001886 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001887 }
1888 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001889 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001890 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001891 }
1892 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001893 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001894}
1895
Ethan Nicholascc305772017-10-13 16:17:45 -04001896void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1897 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001898 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001899 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001900 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001901 this->write(");");
1902}
1903
1904void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1905 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001906 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001907 this->writeLine(") {");
1908 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001909 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
1910 const SwitchCase& c = stmt->as<SwitchCase>();
1911 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001912 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05001913 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001914 this->writeLine(":");
1915 } else {
1916 this->writeLine("default:");
1917 }
John Stilesb23a64b2021-03-11 08:27:59 -05001918 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05001919 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05001920 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05001921 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05001922 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04001923 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001924 }
1925 fIndentation--;
1926 this->write("}");
1927}
1928
John Stiles986c7fb2020-12-01 14:44:56 -05001929void MetalCodeGenerator::writeReturnStatementFromMain() {
1930 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05001931 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001932 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05001933 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001934 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001935 case ProgramKind::kVertex:
John Stilesf7410bd2021-01-19 13:07:55 -05001936 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001937 break;
1938 default:
1939 SkDEBUGFAIL("unsupported kind of program");
1940 }
1941}
1942
Ethan Nicholascc305772017-10-13 16:17:45 -04001943void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04001944 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001945 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001946 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1947 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001948 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001949 this->writeLine(";");
1950 } else {
1951 fErrors.error(r.fOffset, "Metal does not support returning '" +
1952 r.expression()->type().description() + "' from main()");
1953 }
John Stiles986c7fb2020-12-01 14:44:56 -05001954 }
1955 this->writeReturnStatementFromMain();
1956 return;
1957 }
1958
Ethan Nicholascc305772017-10-13 16:17:45 -04001959 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001960 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001961 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001962 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001963 }
1964 this->write(";");
1965}
1966
Michael Ludwigbf58add2021-03-16 10:40:11 -04001967void MetalCodeGenerator::writeHeader() {
1968 this->write("#include <metal_stdlib>\n");
1969 this->write("#include <simd/simd.h>\n");
1970 this->write("using namespace metal;\n");
1971}
1972
Ethan Nicholascc305772017-10-13 16:17:45 -04001973void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001974 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001975 if (e->is<GlobalVarDeclaration>()) {
1976 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001977 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001978 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001979 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001980 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001981 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001982 if (-1 == fUniformBuffer) {
1983 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001984 fUniformBuffer = uniformSet;
1985 } else if (uniformSet != fUniformBuffer) {
1986 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1987 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001988 }
1989 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001990 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001991 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001992 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001993 this->write(";\n");
1994 }
1995 }
1996 }
1997 if (-1 != fUniformBuffer) {
1998 this->write("};\n");
1999 }
2000}
2001
2002void MetalCodeGenerator::writeInputStruct() {
2003 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002004 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002005 if (e->is<GlobalVarDeclaration>()) {
2006 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002007 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002008 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2009 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002010 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002011 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002012 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002013 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002014 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002015 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002016 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002017 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002018 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002019 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002020 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002021 }
2022 }
2023 this->write(";\n");
2024 }
2025 }
2026 }
2027 this->write("};\n");
2028}
2029
2030void MetalCodeGenerator::writeOutputStruct() {
2031 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002032 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002033 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002034 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002035 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002036 }
Brian Osman133724c2020-10-28 14:14:39 -04002037 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002038 if (e->is<GlobalVarDeclaration>()) {
2039 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002040 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002041 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2042 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002043 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002044 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002045 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002046 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002047
2048 int location = var.modifiers().fLayout.fLocation;
2049 if (location < 0) {
2050 fErrors.error(var.fOffset,
2051 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002052 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002053 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002054 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002055 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002056 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002057 if (colorIndex) {
2058 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002059 }
Brian Osmanc0213602020-10-06 14:43:32 -04002060 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002061 }
2062 this->write(";\n");
2063 }
2064 }
Timothy Liang7d637782018-06-05 09:58:07 -04002065 }
John Stiles270cec22021-02-17 12:59:36 -05002066 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002067 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002068 }
2069 this->write("};\n");
2070}
2071
2072void MetalCodeGenerator::writeInterfaceBlocks() {
2073 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002074 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002075 if (e->is<InterfaceBlock>()) {
2076 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002077 wroteInterfaceBlock = true;
2078 }
2079 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002080 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002081 this->writeLine("struct sksl_synthetic_uniforms {");
2082 this->writeLine(" float u_skRTHeight;");
2083 this->writeLine("};");
2084 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002085}
2086
John Stilesdc75a972020-11-25 16:24:55 -05002087void MetalCodeGenerator::writeStructDefinitions() {
2088 for (const ProgramElement* e : fProgram.elements()) {
2089 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002090 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002091 }
2092 }
2093}
2094
John Stilescdcdb042020-07-06 09:03:51 -04002095void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2096 // Visit the interface blocks.
2097 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002098 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002099 }
Brian Osman133724c2020-10-28 14:14:39 -04002100 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002101 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002102 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002103 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002104 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2105 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2106 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002107 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002108 var.type().typeKind() == Type::TypeKind::kSampler) {
2109 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2110 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002111 visitor->visitTexture(var.type(), var.name());
2112 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002113 } else {
2114 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002115 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002116 }
2117 }
2118 }
John Stilescdcdb042020-07-06 09:03:51 -04002119}
2120
2121void MetalCodeGenerator::writeGlobalStruct() {
2122 class : public GlobalStructVisitor {
2123 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002124 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002125 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002126 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002127 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002128 fCodeGen->write("* ");
2129 fCodeGen->writeName(blockName);
2130 fCodeGen->write(";\n");
2131 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002132 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002133 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002134 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002135 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002136 fCodeGen->write(" ");
2137 fCodeGen->writeName(name);
2138 fCodeGen->write(";\n");
2139 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002140 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002141 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002142 fCodeGen->write(" sampler ");
2143 fCodeGen->writeName(name);
2144 fCodeGen->write(";\n");
2145 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002146 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002147 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002148 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002149 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002150 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002151 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002152 fCodeGen->write(";\n");
2153 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002154 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002155 if (fFirst) {
2156 fCodeGen->write("struct Globals {\n");
2157 fFirst = false;
2158 }
2159 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002160 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002161 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002162 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002163 fFirst = true;
2164 }
2165 }
2166
2167 MetalCodeGenerator* fCodeGen = nullptr;
2168 bool fFirst = true;
2169 } visitor;
2170
2171 visitor.fCodeGen = this;
2172 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002173 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002174}
2175
2176void MetalCodeGenerator::writeGlobalInit() {
2177 class : public GlobalStructVisitor {
2178 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002179 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002180 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002181 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002182 fCodeGen->write("&");
2183 fCodeGen->writeName(blockName);
2184 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002185 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002186 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002187 fCodeGen->writeName(name);
2188 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002189 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002190 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002191 fCodeGen->writeName(name);
2192 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002193 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002194 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002195 if (value) {
2196 fCodeGen->writeVarInitializer(var, *value);
2197 } else {
2198 fCodeGen->write("{}");
2199 }
2200 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002201 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002202 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002203 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002204 fFirst = false;
2205 } else {
2206 fCodeGen->write(", ");
2207 }
2208 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002209 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002210 if (!fFirst) {
2211 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002212 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002213 }
2214 }
2215 MetalCodeGenerator* fCodeGen = nullptr;
2216 bool fFirst = true;
2217 } visitor;
2218
2219 visitor.fCodeGen = this;
2220 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002221 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002222}
2223
Ethan Nicholascc305772017-10-13 16:17:45 -04002224void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002225 switch (e.kind()) {
2226 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002227 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002228 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002229 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2230 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2231 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002232 if (-1 == builtin) {
2233 // normal var
2234 this->writeVarDeclaration(decl, true);
John Stilese8b5a732021-03-12 13:25:52 -05002235 this->finishLine();
Brian Osmanc0213602020-10-06 14:43:32 -04002236 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2237 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002238 }
2239 break;
2240 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002241 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002242 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002243 break;
John Stilesdc75a972020-11-25 16:24:55 -05002244 case ProgramElement::Kind::kStructDefinition:
2245 // Handled in writeStructDefinitions. Do nothing.
2246 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002247 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002248 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002249 break;
John Stiles569249b2020-11-03 12:18:22 -05002250 case ProgramElement::Kind::kFunctionPrototype:
2251 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2252 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002253 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002254 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2255 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002256 this->writeLine(";");
2257 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002258 case ProgramElement::Kind::kEnum:
2259 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002260 default:
John Stileseada7bc2021-02-02 16:29:32 -05002261 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002262 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002263 }
2264}
2265
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002266MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2267 if (!e) {
2268 return kNo_Requirements;
2269 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002270 switch (e->kind()) {
2271 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002272 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002273 Requirements result = this->requirements(f.function());
2274 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002275 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002276 }
2277 return result;
2278 }
John Stiles8cad6372021-04-07 12:31:13 -04002279 case Expression::Kind::kConstructorCompound:
2280 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002281 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002282 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002283 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002284 case Expression::Kind::kConstructorSplat:
2285 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002286 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002287 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002288 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002289 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002290 }
2291 return result;
2292 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002293 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002294 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002295 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002296 return kGlobals_Requirement;
2297 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002298 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002299 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002300 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002301 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002302 case Expression::Kind::kBinary: {
2303 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002304 return this->requirements(bin.left().get()) |
2305 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002306 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002307 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002308 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002309 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002310 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002311 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002312 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002313 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002314 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002315 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002316 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002317 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2318 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002319 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002320 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002321 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002322 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002323 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002324 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002325 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002326 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002327 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002328 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002329 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002330 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002331 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002332 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002333 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002334 } else {
2335 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002336 }
2337 }
2338 return result;
2339 }
2340 default:
2341 return kNo_Requirements;
2342 }
2343}
2344
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002345MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2346 if (!s) {
2347 return kNo_Requirements;
2348 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002349 switch (s->kind()) {
2350 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002351 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002352 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002353 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002354 }
2355 return result;
2356 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002357 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002358 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002359 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002360 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002361 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002362 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002363 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002364 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002365 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002366 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002367 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002368 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002369 return this->requirements(i.test().get()) |
2370 this->requirements(i.ifTrue().get()) |
2371 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002372 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002373 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002374 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002375 return this->requirements(f.initializer().get()) |
2376 this->requirements(f.test().get()) |
2377 this->requirements(f.next().get()) |
2378 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002379 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002380 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002381 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002382 return this->requirements(d.test().get()) |
2383 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002384 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002385 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002386 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002387 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002388 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2389 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002390 }
2391 return result;
2392 }
2393 default:
2394 return kNo_Requirements;
2395 }
2396}
2397
2398MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002399 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002400 return kNo_Requirements;
2401 }
2402 auto found = fRequirements.find(&f);
2403 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002404 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002405 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002406 if (e->is<FunctionDefinition>()) {
2407 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002408 if (&def.declaration() == &f) {
2409 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002410 fRequirements[&f] = reqs;
2411 return reqs;
2412 }
2413 }
2414 }
John Stiles569249b2020-11-03 12:18:22 -05002415 // We never found a definition for this declared function, but it's legal to prototype a
2416 // function without ever giving a definition, as long as you don't call it.
2417 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002418 }
2419 return found->second;
2420}
2421
Timothy Liangb8eeb802018-07-23 16:46:16 -04002422bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002423 StringStream header;
2424 {
2425 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002426 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002427 this->writeStructDefinitions();
2428 this->writeUniformStruct();
2429 this->writeInputStruct();
2430 this->writeOutputStruct();
2431 this->writeInterfaceBlocks();
2432 this->writeGlobalStruct();
2433 }
2434 StringStream body;
2435 {
2436 AutoOutputStream outputToBody(this, &body, &fIndentation);
2437 for (const ProgramElement* e : fProgram.elements()) {
2438 this->writeProgramElement(*e);
2439 }
2440 }
2441 write_stringstream(header, *fOut);
2442 write_stringstream(fExtraFunctions, *fOut);
2443 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002444 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002445}
2446
John Stilesa6841be2020-08-06 14:11:56 -04002447} // namespace SkSL