blob: 88666b3302e6f89aa134119a2c885c662ce1320b [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050013#include "src/sksl/ir/SkSLExpressionStatement.h"
14#include "src/sksl/ir/SkSLExtension.h"
15#include "src/sksl/ir/SkSLIndexExpression.h"
16#include "src/sksl/ir/SkSLModifiersDeclaration.h"
17#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050018#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040020
Brian Osmanc262a122020-08-06 16:34:34 -040021#include <algorithm>
22
Ethan Nicholascc305772017-10-13 16:17:45 -040023namespace SkSL {
24
John Stilesd6449e92020-11-30 09:13:23 -050025const char* MetalCodeGenerator::OperatorName(Token::Kind op) {
26 switch (op) {
27 case Token::Kind::TK_LOGICALXOR: return "!=";
Brian Osman00185012021-02-04 16:07:11 -050028 default: return Operators::OperatorName(op);
John Stilesd6449e92020-11-30 09:13:23 -050029 }
30}
31
John Stilescdcdb042020-07-06 09:03:51 -040032class MetalCodeGenerator::GlobalStructVisitor {
33public:
34 virtual ~GlobalStructVisitor() = default;
John Stilesfdb8dbe2020-12-04 11:00:03 -050035 virtual void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) = 0;
36 virtual void visitTexture(const Type& type, const String& name) = 0;
37 virtual void visitSampler(const Type& type, const String& name) = 0;
38 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040039};
40
Timothy Liangee84fe12018-05-18 14:38:19 -040041void MetalCodeGenerator::setupIntrinsics() {
John Stilesd7199b22020-12-30 16:22:58 -050042 fIntrinsicMap[String("atan")] = kAtan_IntrinsicKind;
43 fIntrinsicMap[String("floatBitsToInt")] = kBitcast_IntrinsicKind;
44 fIntrinsicMap[String("floatBitsToUint")] = kBitcast_IntrinsicKind;
45 fIntrinsicMap[String("intBitsToFloat")] = kBitcast_IntrinsicKind;
46 fIntrinsicMap[String("uintBitsToFloat")] = kBitcast_IntrinsicKind;
47 fIntrinsicMap[String("equal")] = kCompareEqual_IntrinsicKind;
48 fIntrinsicMap[String("notEqual")] = kCompareNotEqual_IntrinsicKind;
49 fIntrinsicMap[String("lessThan")] = kCompareLessThan_IntrinsicKind;
50 fIntrinsicMap[String("lessThanEqual")] = kCompareLessThanEqual_IntrinsicKind;
51 fIntrinsicMap[String("greaterThan")] = kCompareGreaterThan_IntrinsicKind;
52 fIntrinsicMap[String("greaterThanEqual")] = kCompareGreaterThanEqual_IntrinsicKind;
53 fIntrinsicMap[String("degrees")] = kDegrees_IntrinsicKind;
54 fIntrinsicMap[String("dFdx")] = kDFdx_IntrinsicKind;
55 fIntrinsicMap[String("dFdy")] = kDFdy_IntrinsicKind;
56 fIntrinsicMap[String("distance")] = kDistance_IntrinsicKind;
57 fIntrinsicMap[String("dot")] = kDot_IntrinsicKind;
58 fIntrinsicMap[String("faceforward")] = kFaceforward_IntrinsicKind;
59 fIntrinsicMap[String("bitCount")] = kBitCount_IntrinsicKind;
60 fIntrinsicMap[String("findLSB")] = kFindLSB_IntrinsicKind;
61 fIntrinsicMap[String("findMSB")] = kFindMSB_IntrinsicKind;
62 fIntrinsicMap[String("inverse")] = kInverse_IntrinsicKind;
63 fIntrinsicMap[String("inversesqrt")] = kInversesqrt_IntrinsicKind;
64 fIntrinsicMap[String("length")] = kLength_IntrinsicKind;
65 fIntrinsicMap[String("matrixCompMult")] = kMatrixCompMult_IntrinsicKind;
66 fIntrinsicMap[String("mod")] = kMod_IntrinsicKind;
67 fIntrinsicMap[String("normalize")] = kNormalize_IntrinsicKind;
68 fIntrinsicMap[String("radians")] = kRadians_IntrinsicKind;
69 fIntrinsicMap[String("reflect")] = kReflect_IntrinsicKind;
70 fIntrinsicMap[String("refract")] = kRefract_IntrinsicKind;
John Stiles23456532020-12-30 18:12:48 -050071 fIntrinsicMap[String("roundEven")] = kRoundEven_IntrinsicKind;
John Stilesd7199b22020-12-30 16:22:58 -050072 fIntrinsicMap[String("sample")] = kTexture_IntrinsicKind;
Timothy Liangee84fe12018-05-18 14:38:19 -040073}
74
Ethan Nicholascc305772017-10-13 16:17:45 -040075void MetalCodeGenerator::write(const char* s) {
76 if (!s[0]) {
77 return;
78 }
79 if (fAtLineStart) {
80 for (int i = 0; i < fIndentation; i++) {
81 fOut->writeText(" ");
82 }
83 }
84 fOut->writeText(s);
85 fAtLineStart = false;
86}
87
88void MetalCodeGenerator::writeLine(const char* s) {
89 this->write(s);
90 fOut->writeText(fLineEnding);
91 fAtLineStart = true;
92}
93
94void MetalCodeGenerator::write(const String& s) {
95 this->write(s.c_str());
96}
97
98void MetalCodeGenerator::writeLine(const String& s) {
99 this->writeLine(s.c_str());
100}
101
102void MetalCodeGenerator::writeLine() {
103 this->writeLine("");
104}
105
106void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400107 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400108}
109
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500110String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400111 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -0500112 case Type::TypeKind::kArray:
113 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
114 return String::printf("array<%s, %d>",
115 this->typeName(type.componentType()).c_str(), type.columns());
116
Ethan Nicholase6592142020-09-08 10:22:09 -0400117 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500118 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -0500119
Ethan Nicholase6592142020-09-08 10:22:09 -0400120 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500121 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
122 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -0500123
Ethan Nicholase6592142020-09-08 10:22:09 -0400124 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500125 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -0500126
John Stilesfd41d872020-11-25 22:39:45 -0500127 case Type::TypeKind::kEnum:
128 return "int";
John Stilesb4418502021-02-04 10:57:08 -0500129
Ethan Nicholascc305772017-10-13 16:17:45 -0400130 default:
John Stiles54e7c052021-01-11 14:22:36 -0500131 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -0400132 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
John Stiles54e7c052021-01-11 14:22:36 -0500133 return fContext.fTypes.fFloat->name();
134 } else if (type == *fContext.fTypes.fByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500135 return "char";
John Stiles54e7c052021-01-11 14:22:36 -0500136 } else if (type == *fContext.fTypes.fUByte) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500137 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400138 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500139 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400140 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400141 }
142}
143
Brian Osman02bc5222021-01-28 11:00:20 -0500144void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
145 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500146 this->writeLine("struct " + type.name() + " {");
147 fIndentation++;
148 this->writeFields(type.fields(), type.fOffset);
149 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500150 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500151}
152
John Stilesb4418502021-02-04 10:57:08 -0500153void MetalCodeGenerator::writeType(const Type& type) {
154 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500155}
156
Ethan Nicholascc305772017-10-13 16:17:45 -0400157void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 switch (expr.kind()) {
159 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400160 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400161 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400162 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400163 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400164 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400165 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400166 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400167 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400168 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400169 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400170 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400171 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400172 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400173 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400174 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400175 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400176 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400177 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400178 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400179 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400180 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400181 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400182 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400183 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400184 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400185 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400186 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400187 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400189 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400190 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400192 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400193 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400196 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400199 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400200 break;
201 default:
John Stileseada7bc2021-02-02 16:29:32 -0500202 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500203 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400204 }
205}
206
John Stiles06b84ef2020-12-09 12:35:48 -0500207String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
208 const ExpressionArray& arguments,
209 const SkTArray<VariableReference*>& outVars) {
210 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
211 const FunctionDeclaration& function = call.function();
212
213 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) + "_" + function.name();
214 const char* separator = "";
215
216 // Emit a prototype for the function we'll be calling through to in our helper.
217 if (!function.isBuiltin()) {
218 this->writeFunctionDeclaration(function);
219 this->writeLine(";");
220 }
221
222 // Synthesize a helper function that takes the same inputs as `function`, except in places where
223 // `outVars` is non-null; in those places, we take the type of the VariableReference.
224 //
225 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500226 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500227 this->write(" ");
228 this->write(name);
229 this->write("(");
230 this->writeFunctionRequirementParams(function, separator);
231
232 SkASSERT(outVars.size() == arguments.size());
233 SkASSERT(outVars.size() == function.parameters().size());
234
John Stiles73e2c892021-02-13 13:58:01 -0500235 // We need to detect cases where the caller passes the same variable as an out-param more than
236 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
237 // redundant input parameter entirely, and not give it any name.)
238 std::unordered_set<const Variable*> writtenVars;
239
John Stiles06b84ef2020-12-09 12:35:48 -0500240 for (int index = 0; index < arguments.count(); ++index) {
241 this->write(separator);
242 separator = ", ";
243
244 const Variable* param = function.parameters()[index];
245 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
246
247 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500248 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500249
250 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
251 this->write("&");
252 }
253 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500254 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
255 if (didInsert) {
256 this->write(" ");
257 fIgnoreVariableReferenceModifiers = true;
258 this->writeVariableReference(*outVars[index]);
259 fIgnoreVariableReferenceModifiers = false;
260 }
John Stiles06b84ef2020-12-09 12:35:48 -0500261 } else {
262 this->write(" _var");
263 this->write(to_string(index));
264 }
John Stiles06b84ef2020-12-09 12:35:48 -0500265 }
266 this->writeLine(") {");
267
268 ++fIndentation;
269 for (int index = 0; index < outVars.count(); ++index) {
270 if (!outVars[index]) {
271 continue;
272 }
273 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500274 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500275 this->write(" _var");
276 this->write(to_string(index));
277
278 const Variable* param = function.parameters()[index];
279 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
280 this->write(" = ");
281 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500282 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500283 fIgnoreVariableReferenceModifiers = false;
284 }
285
286 this->writeLine(";");
287 }
288
John Stilesf7410bd2021-01-19 13:07:55 -0500289 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500290 bool hasResult = (call.type().name() != "void");
291 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500292 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500293 this->write(" _skResult = ");
294 }
295
296 this->writeName(function.name());
297 this->write("(");
298 separator = "";
299 this->writeFunctionRequirementArgs(function, separator);
300
301 for (int index = 0; index < arguments.count(); ++index) {
302 this->write(separator);
303 separator = ", ";
304
305 this->write("_var");
306 this->write(to_string(index));
307 }
308 this->writeLine(");");
309
310 for (int index = 0; index < outVars.count(); ++index) {
311 if (!outVars[index]) {
312 continue;
313 }
314 // outParam.zyx = _var2;
315 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500316 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500317 fIgnoreVariableReferenceModifiers = false;
318 this->write(" = _var");
319 this->write(to_string(index));
320 this->writeLine(";");
321 }
322
323 if (hasResult) {
324 this->writeLine("return _skResult;");
325 }
326
327 --fIndentation;
328 this->writeLine("}");
329
330 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500331}
332
John Stilesf64e4072020-12-10 10:34:27 -0500333String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
334 return "as_type<" + outType.displayName() + ">";
335}
336
Ethan Nicholascc305772017-10-13 16:17:45 -0400337void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400338 const FunctionDeclaration& function = c.function();
John Stiles89ac7c22020-12-30 17:47:31 -0500339 // If this function is a built-in with no declaration, it's probably an intrinsic and might need
340 // special handling.
341 if (function.isBuiltin() && !function.definition()) {
342 auto iter = fIntrinsicMap.find(function.name());
343 if (iter != fIntrinsicMap.end()) {
344 this->writeIntrinsicCall(c, iter->second);
345 return;
346 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400347 }
John Stilesb21fac22020-12-04 15:36:49 -0500348
John Stilesd7199b22020-12-30 16:22:58 -0500349 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
350 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
351 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
352 // allow a swizzle to be passed to a `floatN&`.)
353 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500354 const std::vector<const Variable*>& parameters = function.parameters();
355 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500356
357 bool foundOutParam = false;
358 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500359 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500360
361 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500362 // If this is an out parameter...
363 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500364 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500365 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500366 // Assignability was verified at IRGeneration time, so this should always succeed.
367 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
368 outVars[index] = info.fAssignedVar;
369 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500370 }
371 }
372
John Stiles06b84ef2020-12-09 12:35:48 -0500373 if (foundOutParam) {
374 // Out parameters need to be written back to at the end of the function. To do this, we
375 // synthesize a helper function which evaluates the out-param expression into a temporary
376 // variable, calls the original function, then writes the temp var back into the out param
377 // using the original out-param expression. (This lets us support things like swizzles and
378 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500379 this->write(getOutParamHelper(c, arguments, outVars));
380 } else {
381 this->write(function.name());
John Stiles06b84ef2020-12-09 12:35:48 -0500382 }
383
Ethan Nicholascc305772017-10-13 16:17:45 -0400384 this->write("(");
385 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500386 this->writeFunctionRequirementArgs(function, separator);
387 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400388 this->write(separator);
389 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500390
391 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500392 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500393 } else {
Brian Osman00185012021-02-04 16:07:11 -0500394 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500395 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400396 }
397 this->write(")");
398}
399
Brian Osman964f0a02020-12-29 10:15:22 -0500400static constexpr char kInverse2x2[] = R"(
401float2x2 float2x2_inverse(float2x2 m) {
402 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
403}
404)";
405
406static constexpr char kInverse3x3[] = R"(
407float3x3 float3x3_inverse(float3x3 m) {
408 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
409 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
410 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
411 float b01 = a22*a11 - a12*a21;
412 float b11 = -a22*a10 + a12*a20;
413 float b21 = a21*a10 - a11*a20;
414 float det = a00*b01 + a01*b11 + a02*b21;
415 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
416 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
417 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
418}
419)";
420
421static constexpr char kInverse4x4[] = R"(
422float4x4 float4x4_inverse(float4x4 m) {
423 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
424 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
425 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
426 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
427 float b00 = a00*a11 - a01*a10;
428 float b01 = a00*a12 - a02*a10;
429 float b02 = a00*a13 - a03*a10;
430 float b03 = a01*a12 - a02*a11;
431 float b04 = a01*a13 - a03*a11;
432 float b05 = a02*a13 - a03*a12;
433 float b06 = a20*a31 - a21*a30;
434 float b07 = a20*a32 - a22*a30;
435 float b08 = a20*a33 - a23*a30;
436 float b09 = a21*a32 - a22*a31;
437 float b10 = a21*a33 - a23*a31;
438 float b11 = a22*a33 - a23*a32;
439 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
440 return float4x4(a11*b11 - a12*b10 + a13*b09,
441 a02*b10 - a01*b11 - a03*b09,
442 a31*b05 - a32*b04 + a33*b03,
443 a22*b04 - a21*b05 - a23*b03,
444 a12*b08 - a10*b11 - a13*b07,
445 a00*b11 - a02*b08 + a03*b07,
446 a32*b02 - a30*b05 - a33*b01,
447 a20*b05 - a22*b02 + a23*b01,
448 a10*b10 - a11*b08 + a13*b06,
449 a01*b08 - a00*b10 - a03*b06,
450 a30*b04 - a31*b02 + a33*b00,
451 a21*b02 - a20*b04 - a23*b00,
452 a11*b07 - a10*b09 - a12*b06,
453 a00*b09 - a01*b07 + a02*b06,
454 a31*b01 - a30*b03 - a32*b00,
455 a20*b03 - a21*b01 + a22*b00) * (1/det);
456}
457)";
458
John Stilesd7199b22020-12-30 16:22:58 -0500459String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
460 // Only use polyfills for a function taking a single-argument square matrix.
461 if (arguments.size() == 1) {
462 const Type& type = arguments.front()->type();
463 if (type.isMatrix() && type.rows() == type.columns()) {
464 // Inject the correct polyfill based on the matrix size.
465 String name = this->typeName(type) + "_inverse";
466 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
467 if (didInsert) {
468 switch (type.rows()) {
469 case 2:
470 fExtraFunctions.writeText(kInverse2x2);
471 break;
472 case 3:
473 fExtraFunctions.writeText(kInverse3x3);
474 break;
475 case 4:
476 fExtraFunctions.writeText(kInverse4x4);
477 break;
478 }
479 }
480 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500481 }
482 }
John Stilesd7199b22020-12-30 16:22:58 -0500483 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
484 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500485}
486
Brian Osman93aed9a2020-12-28 15:18:46 -0500487static constexpr char kMatrixCompMult[] = R"(
488template <int C, int R>
489matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
490 matrix<float, C, R> result;
491 for (int c = 0; c < C; ++c) {
492 result[c] = a[c] * b[c];
493 }
494 return result;
495}
496)";
497
498void MetalCodeGenerator::writeMatrixCompMult() {
499 String name = "matrixCompMult";
500 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
501 fWrittenIntrinsics.insert(name);
502 fExtraFunctions.writeText(kMatrixCompMult);
503 }
504}
505
John Stiles86424eb2020-12-11 11:17:14 -0500506String MetalCodeGenerator::getTempVariable(const Type& type) {
507 String tempVar = "_skTemp" + to_string(fVarCount++);
508 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
509 return tempVar;
510}
511
John Stiles791c27d2020-12-30 14:56:57 -0500512void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
513 // Write out an intrinsic function call exactly as-is. No muss no fuss.
514 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500515 this->writeArgumentList(c.arguments());
516}
517
518void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500519 this->write("(");
520 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500521 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500522 this->write(separator);
523 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500524 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500525 }
526 this->write(")");
527}
528
John Stilesd7199b22020-12-30 16:22:58 -0500529void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400530 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400531 switch (kind) {
John Stilesd7199b22020-12-30 16:22:58 -0500532 case kTexture_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500533 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400534 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500535 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400536 this->write(SAMPLER_SUFFIX);
537 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400538 const Type& arg1Type = arguments[1]->type();
John Stiles54e7c052021-01-11 14:22:36 -0500539 if (arg1Type == *fContext.fTypes.fFloat3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500540 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500541 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500542 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500543 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500544 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400545 } else {
John Stiles54e7c052021-01-11 14:22:36 -0500546 SkASSERT(arg1Type == *fContext.fTypes.fFloat2);
Brian Osman00185012021-02-04 16:07:11 -0500547 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400548 this->write(")");
549 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400550 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400551 }
John Stilesd7199b22020-12-30 16:22:58 -0500552 case kMod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400553 // 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 -0500554 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500555 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500556 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500557 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500558 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500559 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500560 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400561 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500562 }
Brian Osman46787d52020-11-24 14:18:23 -0500563 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stilesd7199b22020-12-30 16:22:58 -0500564 case kDistance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500565 if (arguments[0]->type().columns() == 1) {
566 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500567 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500568 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500569 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500570 this->write(")");
571 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500572 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500573 }
574 break;
575 }
John Stilesd7199b22020-12-30 16:22:58 -0500576 case kDot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500577 if (arguments[0]->type().columns() == 1) {
578 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500579 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500580 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500581 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500582 this->write(")");
583 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500584 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500585 }
586 break;
587 }
John Stilesd7199b22020-12-30 16:22:58 -0500588 case kFaceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500589 if (arguments[0]->type().columns() == 1) {
590 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
591 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500592 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500593 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500594 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500595 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500596 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500597 this->write("))");
598 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500599 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500600 }
601 break;
602 }
John Stilesd7199b22020-12-30 16:22:58 -0500603 case kLength_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500604 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500605 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500606 this->write(")");
607 break;
608 }
John Stilesd7199b22020-12-30 16:22:58 -0500609 case kNormalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500610 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500611 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500612 this->write(")");
613 break;
614 }
John Stilesd7199b22020-12-30 16:22:58 -0500615 case kBitcast_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500616 this->write(this->getBitcastIntrinsic(c.type()));
617 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500618 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500619 this->write(")");
620 break;
621 }
John Stilesd7199b22020-12-30 16:22:58 -0500622 case kDegrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500623 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500624 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500625 this->write(") * 57.2957795)");
626 break;
627 }
John Stilesd7199b22020-12-30 16:22:58 -0500628 case kRadians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500629 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500630 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500631 this->write(") * 0.0174532925)");
632 break;
633 }
John Stilesd7199b22020-12-30 16:22:58 -0500634 case kDFdx_IntrinsicKind: {
635 this->write("dfdx");
636 this->writeArgumentList(c.arguments());
637 break;
638 }
639 case kDFdy_IntrinsicKind: {
640 // Flipping Y also negates the Y derivatives.
641 if (fProgram.fSettings.fFlipY) {
642 this->write("-");
643 }
644 this->write("dfdy");
645 this->writeArgumentList(c.arguments());
646 break;
647 }
648 case kInverse_IntrinsicKind: {
649 this->write(this->getInversePolyfill(arguments));
650 this->writeArgumentList(c.arguments());
651 break;
652 }
653 case kInversesqrt_IntrinsicKind: {
654 this->write("rsqrt");
655 this->writeArgumentList(c.arguments());
656 break;
657 }
658 case kAtan_IntrinsicKind: {
659 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
660 this->writeArgumentList(c.arguments());
661 break;
662 }
663 case kReflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500664 if (arguments[0]->type().columns() == 1) {
665 // We need to synthesize `I - 2 * N * I * N`.
666 String tmpI = this->getTempVariable(arguments[0]->type());
667 String tmpN = this->getTempVariable(arguments[1]->type());
668
669 // (_skTempI = ...
670 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500671 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500672
673 // , _skTempN = ...
674 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500675 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500676
677 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
678 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
679 } else {
680 this->writeSimpleIntrinsic(c);
681 }
682 break;
683 }
John Stilesd7199b22020-12-30 16:22:58 -0500684 case kRefract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500685 if (arguments[0]->type().columns() == 1) {
686 // Metal does implement refract for vectors; rather than reimplementing refract from
687 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
688 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500689 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500690 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500691 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500692 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500693 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500694 this->write(").x)");
695 } else {
696 this->writeSimpleIntrinsic(c);
697 }
698 break;
699 }
John Stiles23456532020-12-30 18:12:48 -0500700 case kRoundEven_IntrinsicKind: {
701 this->write("rint");
702 this->writeArgumentList(c.arguments());
703 break;
704 }
John Stilesd7199b22020-12-30 16:22:58 -0500705 case kBitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500706 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500707 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500708 this->write(")");
709 break;
710 }
John Stilesd7199b22020-12-30 16:22:58 -0500711 case kFindLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500712 // Create a temp variable to store the expression, to avoid double-evaluating it.
713 String skTemp = this->getTempVariable(arguments[0]->type());
714 String exprType = this->typeName(arguments[0]->type());
715
716 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
717 // Use select to detect zero inputs and force a -1 result.
718
719 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
720 this->write("(");
721 this->write(skTemp);
722 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500723 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500724 this->write("), select(ctz(");
725 this->write(skTemp);
726 this->write("), ");
727 this->write(exprType);
728 this->write("(-1), ");
729 this->write(skTemp);
730 this->write(" == ");
731 this->write(exprType);
732 this->write("(0)))");
733 break;
734 }
John Stilesd7199b22020-12-30 16:22:58 -0500735 case kFindMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500736 // Create a temp variable to store the expression, to avoid double-evaluating it.
737 String skTemp1 = this->getTempVariable(arguments[0]->type());
738 String exprType = this->typeName(arguments[0]->type());
739
740 // GLSL findMSB is actually quite different from Metal's clz:
741 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
742 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
743
744 // (_skTemp1 = (.....),
745 this->write("(");
746 this->write(skTemp1);
747 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500748 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500749 this->write("), ");
750
751 // Signed input types might be negative; we need another helper variable to negate the
752 // input (since we can only find one bits, not zero bits).
753 String skTemp2;
754 if (arguments[0]->type().isSigned()) {
755 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
756 skTemp2 = this->getTempVariable(arguments[0]->type());
757 this->write(skTemp2);
758 this->write(" = (select(");
759 this->write(skTemp1);
760 this->write(", ~");
761 this->write(skTemp1);
762 this->write(", ");
763 this->write(skTemp1);
764 this->write(" < 0)), ");
765 } else {
766 skTemp2 = skTemp1;
767 }
768
769 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
770 this->write("select(");
771 this->write(this->typeName(c.type()));
772 this->write("(clz(");
773 this->write(skTemp2);
774 this->write(")), ");
775 this->write(this->typeName(c.type()));
776 this->write("(-1), ");
777 this->write(skTemp2);
778 this->write(" == ");
779 this->write(exprType);
780 this->write("(0)))");
781 break;
782 }
John Stilesd7199b22020-12-30 16:22:58 -0500783 case kMatrixCompMult_IntrinsicKind: {
784 this->writeMatrixCompMult();
785 this->writeSimpleIntrinsic(c);
786 break;
787 }
788 case kCompareEqual_IntrinsicKind:
789 case kCompareGreaterThan_IntrinsicKind:
790 case kCompareGreaterThanEqual_IntrinsicKind:
791 case kCompareLessThan_IntrinsicKind:
792 case kCompareLessThanEqual_IntrinsicKind:
793 case kCompareNotEqual_IntrinsicKind: {
794 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500795 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500796 switch (kind) {
797 case kCompareEqual_IntrinsicKind:
798 this->write(" == ");
799 break;
800 case kCompareNotEqual_IntrinsicKind:
801 this->write(" != ");
802 break;
803 case kCompareLessThan_IntrinsicKind:
804 this->write(" < ");
805 break;
806 case kCompareLessThanEqual_IntrinsicKind:
807 this->write(" <= ");
808 break;
809 case kCompareGreaterThan_IntrinsicKind:
810 this->write(" > ");
811 break;
812 case kCompareGreaterThanEqual_IntrinsicKind:
813 this->write(" >= ");
814 break;
815 default:
John Stilesf57207b2021-02-02 17:50:34 -0500816 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500817 }
Brian Osman00185012021-02-04 16:07:11 -0500818 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500819 this->write(")");
820 break;
821 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400822 default:
John Stilesf57207b2021-02-02 17:50:34 -0500823 SK_ABORT("unsupported intrinsic kind");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400824 }
825}
826
John Stilesfcf8cb22020-08-06 14:29:22 -0400827// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
828// Cells that don't exist in the source matrix will be populated with identity-matrix values.
829void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
830 SkASSERT(rows <= 4);
831 SkASSERT(columns <= 4);
832
833 const char* columnSeparator = "";
834 for (int c = 0; c < columns; ++c) {
835 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
836 columnSeparator = "), ";
837
838 // Determine how many values to take from the source matrix for this row.
839 int swizzleLength = 0;
840 if (c < sourceMatrix.columns()) {
841 swizzleLength = std::min<>(rows, sourceMatrix.rows());
842 }
843
844 // Emit all the values from the source matrix row.
845 bool firstItem;
846 switch (swizzleLength) {
847 case 0: firstItem = true; break;
848 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
849 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
850 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
851 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
852 default: SkUNREACHABLE;
853 }
854
855 // Emit the placeholder identity-matrix cells.
856 for (int r = swizzleLength; r < rows; ++r) {
857 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
858 firstItem = false;
859 }
860 }
861
862 fExtraFunctions.writeText(")");
863}
864
865// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
866// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400867void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
868 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400869 size_t argIndex = 0;
870 int argPosition = 0;
871
872 const char* columnSeparator = "";
873 for (int c = 0; c < columns; ++c) {
874 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
875 columnSeparator = "), ";
876
877 const char* rowSeparator = "";
878 for (int r = 0; r < rows; ++r) {
879 fExtraFunctions.writeText(rowSeparator);
880 rowSeparator = ", ";
881
882 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400883 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400884 switch (argType.typeKind()) {
885 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400886 fExtraFunctions.printf("x%zu", argIndex);
887 break;
888 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400889 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400890 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
891 break;
892 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400893 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400894 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
895 argPosition / argType.rows(),
896 argPosition % argType.rows());
897 break;
898 }
899 default: {
900 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
901 fExtraFunctions.writeText("<error>");
902 break;
903 }
904 }
905
906 ++argPosition;
907 if (argPosition >= argType.columns() * argType.rows()) {
908 ++argIndex;
909 argPosition = 0;
910 }
911 } else {
912 SkDEBUGFAIL("not enough arguments for matrix constructor");
913 fExtraFunctions.writeText("<error>");
914 }
915 }
916 }
917
918 if (argPosition != 0 || argIndex != args.size()) {
919 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
920 fExtraFunctions.writeText(", <error>");
921 }
922
923 fExtraFunctions.writeText(")");
924}
925
John Stiles1bdafbf2020-05-28 12:17:20 -0400926// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
927// Keeps track of previously generated constructors so that we won't generate more than one
928// constructor for any given permutation of input argument types. Returns the name of the
929// generated constructor method.
930String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400931 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500932 int columns = matrix.columns();
933 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400934 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400935
936 // Create the helper-method name and use it as our lookup key.
937 String name;
938 name.appendf("float%dx%d_from", columns, rows);
939 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500940 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400941 }
942
943 // If a helper-method has already been synthesized, we don't need to synthesize it again.
944 auto [iter, newlyCreated] = fHelpers.insert(name);
945 if (!newlyCreated) {
946 return name;
947 }
948
949 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
950 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
951 // supply a mixture of scalars and vectors.)
952 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
953
954 size_t argIndex = 0;
955 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400956 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400957 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500958 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400959 argSeparator = ", ";
960 }
961
962 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
963
John Stiles9aeed132020-11-24 17:36:06 -0500964 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400965 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400966 } else {
967 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400968 }
969
John Stilesfcf8cb22020-08-06 14:29:22 -0400970 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500971 return name;
972}
973
974bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
975 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
976 return false;
977 }
978 if (t1.columns() > 1) {
979 return this->canCoerce(t1.componentType(), t2.componentType());
980 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500981 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500982}
983
John Stiles1bdafbf2020-05-28 12:17:20 -0400984bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
985 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500986 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400987 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500988 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400989
990 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
991 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
992 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
993 // scalars can be constructed trivially. In more complex cases, we generate a helper function
994 // that converts our inputs into a properly-shaped matrix.
995 // A matrix construct helper method is always used if any input argument is a matrix.
996 // Helper methods are also necessary when any argument would span multiple rows. For instance:
997 //
998 // float2 x = (1, 2);
999 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
1000 // | 2 4 6 |
1001 //
1002 // float2 x = (2, 3);
1003 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
1004 // | 2 4 6 |
1005 //
1006 // float4 x = (1, 2, 3, 4);
1007 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
1008 // | 2 4 |
1009 //
1010
1011 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001012 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001013 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -05001014 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001015 return true;
1016 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001017 position += expr->type().columns();
1018 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001019 // An input argument would span multiple rows; a helper function is required.
1020 return true;
1021 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001022 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001023 // We've advanced to the end of a row. Wrap to the start of the next row.
1024 position = 0;
1025 }
1026 }
1027
1028 return false;
1029}
1030
1031void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001032 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001033 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001034 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001035 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001036 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -04001037 const Type& argType = arg.type();
1038 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001039 this->writeExpression(arg, parentPrecedence);
1040 return;
1041 }
1042
1043 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
1044 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -05001045 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001046 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -04001047 this->write("float");
1048 this->write(to_string(matrix.columns()));
1049 this->write("x");
1050 this->write(to_string(matrix.rows()));
1051 this->write("(");
1052 this->writeExpression(arg, parentPrecedence);
1053 this->write(")");
1054 return;
1055 }
1056 }
1057
1058 // Emit and invoke a matrix-constructor helper method if one is necessary.
1059 if (this->matrixConstructHelperIsNeeded(c)) {
1060 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001061 this->write("(");
1062 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001063 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001064 this->write(separator);
1065 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001066 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001067 }
John Stiles1fa15b12020-05-28 17:36:54 +00001068 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001069 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001070 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001071
1072 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stilesb4418502021-02-04 10:57:08 -05001073 this->writeType(constructorType);
1074 this->write(constructorType.isArray() ? "{" : "(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001075 const char* separator = "";
1076 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001077 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001078 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001079 this->write(separator);
1080 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001081 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001082 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001083 // Merge scalars and smaller vectors together.
1084 if (!scalarCount) {
John Stilesb4418502021-02-04 10:57:08 -05001085 this->writeType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001086 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001087 this->write("(");
1088 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001089 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001090 }
Brian Osman00185012021-02-04 16:07:11 -05001091 this->writeExpression(*arg, Precedence::kSequence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001092 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001093 this->write(")");
1094 scalarCount = 0;
1095 }
1096 }
John Stilesb4418502021-02-04 10:57:08 -05001097 this->write(constructorType.isArray() ? "}" : ")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001098}
1099
1100void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001101 if (fRTHeightName.length()) {
1102 this->write("float4(_fragCoord.x, ");
1103 this->write(fRTHeightName.c_str());
1104 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001105 } else {
1106 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1107 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001108}
1109
1110void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001111 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001112 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001113 // we're actually targeting the clones.
1114 if (fIgnoreVariableReferenceModifiers) {
1115 this->writeName(ref.variable()->name());
1116 return;
1117 }
1118
Ethan Nicholas78686922020-10-08 06:46:27 -04001119 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001120 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001121 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001122 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001123 case SK_FRAGCOORD_BUILTIN:
1124 this->writeFragCoord();
1125 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001126 case SK_VERTEXID_BUILTIN:
1127 this->write("sk_VertexID");
1128 break;
1129 case SK_INSTANCEID_BUILTIN:
1130 this->write("sk_InstanceID");
1131 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001132 case SK_CLOCKWISE_BUILTIN:
1133 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001134 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -04001135 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
1136 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001137 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001138 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001139 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001140 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001141 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001142 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001143 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001144 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1145 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001146 this->write("_uniforms.");
1147 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001148 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001149 }
1150 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001151 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001152 }
1153}
1154
1155void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001156 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001157 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001158 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001159 this->write("]");
1160}
1161
1162void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001163 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1164 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001165 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001166 this->write(".");
1167 }
Timothy Liang7d637782018-06-05 09:58:07 -04001168 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001169 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001170 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001171 break;
1172 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001173 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001174 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001175 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001176 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001177 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001178 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1179 this->write("->");
1180 }
Timothy Liang651286f2018-06-07 09:55:33 -04001181 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001182 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001183 }
1184}
1185
1186void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001187 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001188 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001189 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001190 SkASSERT(c >= 0 && c <= 3);
1191 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001192 }
1193}
1194
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001195void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1196 const Type& result) {
John Stiles01cdf012021-02-10 09:53:41 -05001197 String key = "TimesEqual" + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001198
1199 auto [iter, wasInserted] = fHelpers.insert(key);
1200 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001201 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001202 " left = left * right;\n"
1203 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001204 "}\n",
1205 this->typeName(result).c_str(), this->typeName(left).c_str(),
1206 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001207 }
1208}
1209
John Stiles01cdf012021-02-10 09:53:41 -05001210void MetalCodeGenerator::writeMatrixEqualityHelper(const Type& left, const Type& right) {
1211 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1212 left.description().c_str(), right.description().c_str());
1213
1214 String key = "Equality" + this->typeName(left) + ":" + this->typeName(right);
1215
1216 auto [iter, wasInserted] = fHelpers.insert(key);
1217 if (wasInserted) {
1218 fExtraFunctions.printf(
1219 "thread bool operator==(const %s left, const %s right) {\n"
1220 " return",
1221 this->typeName(left).c_str(), this->typeName(right).c_str());
1222
1223 for (int index=0; index<left.columns(); ++index) {
1224 fExtraFunctions.printf("%s all(left[%d] == right[%d])",
1225 index == 0 ? "" : " &&", index, index);
1226 }
1227 fExtraFunctions.printf(";\n"
1228 "}\n");
1229 }
1230}
1231
1232void MetalCodeGenerator::writeMatrixInequalityHelper(const Type& left, const Type& right) {
1233 SkASSERTF(left.rows() == right.rows() && left.columns() == right.columns(), "left=%s, right=%s",
1234 left.description().c_str(), right.description().c_str());
1235
1236 String key = "Inequality" + this->typeName(left) + ":" + this->typeName(right);
1237
1238 auto [iter, wasInserted] = fHelpers.insert(key);
1239 if (wasInserted) {
1240 fExtraFunctions.printf(
1241 "thread bool operator!=(const %s left, const %s right) {\n"
1242 " return",
1243 this->typeName(left).c_str(), this->typeName(right).c_str());
1244
1245 for (int index=0; index<left.columns(); ++index) {
1246 fExtraFunctions.printf("%s any(left[%d] != right[%d])",
1247 index == 0 ? "" : " ||", index, index);
1248 }
1249 fExtraFunctions.printf(";\n"
1250 "}\n");
1251 }
1252}
1253
Ethan Nicholascc305772017-10-13 16:17:45 -04001254void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1255 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001256 const Expression& left = *b.left();
1257 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001258 const Type& leftType = left.type();
1259 const Type& rightType = right.type();
1260 Token::Kind op = b.getOperator();
Brian Osman00185012021-02-04 16:07:11 -05001261 Precedence precedence = Operators::GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001262 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001263 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001264 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001265 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001266 this->write("all");
1267 needParens = true;
1268 }
1269 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001270 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001271 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001272 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001273 needParens = true;
1274 }
1275 break;
1276 default:
1277 break;
1278 }
1279 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001280 this->write("(");
1281 }
John Stiles01cdf012021-02-10 09:53:41 -05001282 if (leftType.isMatrix() && rightType.isMatrix()) {
1283 if (op == Token::Kind::TK_STAREQ) {
1284 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
1285 } else if (op == Token::Kind::TK_EQEQ) {
1286 this->writeMatrixEqualityHelper(leftType, rightType);
1287 } else if (op == Token::Kind::TK_NEQ) {
1288 this->writeMatrixInequalityHelper(leftType, rightType);
1289 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001290 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001291 this->writeExpression(left, precedence);
Brian Osman00185012021-02-04 16:07:11 -05001292 if (op != Token::Kind::TK_EQ && Operators::IsAssignment(op) &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001293 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001294 // This doesn't compile in Metal:
1295 // float4 x = float4(1);
1296 // x.xy *= float2x2(...);
1297 // with the error message "non-const reference cannot bind to vector element",
1298 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1299 // as long as the LHS has no side effects, and hope for the best otherwise.
1300 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001301 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001302 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001303 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001304 SkASSERT(opName.endsWith("="));
1305 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001306 this->write(" ");
1307 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001308 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001309 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001310 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001311 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001312 this->write(")");
1313 }
1314}
1315
1316void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1317 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001318 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001319 this->write("(");
1320 }
Brian Osman00185012021-02-04 16:07:11 -05001321 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001322 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001323 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001324 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001325 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1326 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001327 this->write(")");
1328 }
1329}
1330
1331void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1332 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001333 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001334 this->write("(");
1335 }
John Stilesd6449e92020-11-30 09:13:23 -05001336 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001337 this->writeExpression(*p.operand(), Precedence::kPrefix);
1338 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001339 this->write(")");
1340 }
1341}
1342
1343void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1344 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001345 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001346 this->write("(");
1347 }
Brian Osman00185012021-02-04 16:07:11 -05001348 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001349 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001350 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001351 this->write(")");
1352 }
1353}
1354
1355void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001356 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001357}
1358
1359void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001360 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001361 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001362 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001363 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001364 this->write(to_string(i.value() & 0xffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001365 } else if (type == *fContext.fTypes.fUByte) {
John Stiles12739df2020-12-29 09:47:20 -05001366 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001367 } else {
John Stiles12739df2020-12-29 09:47:20 -05001368 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001369 }
1370}
1371
1372void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001373 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001374}
1375
1376void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001377 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001378}
1379
John Stiles06b84ef2020-12-09 12:35:48 -05001380void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1381 const char*& separator) {
1382 Requirements requirements = this->requirements(f);
1383 if (requirements & kInputs_Requirement) {
1384 this->write(separator);
1385 this->write("_in");
1386 separator = ", ";
1387 }
1388 if (requirements & kOutputs_Requirement) {
1389 this->write(separator);
1390 this->write("_out");
1391 separator = ", ";
1392 }
1393 if (requirements & kUniforms_Requirement) {
1394 this->write(separator);
1395 this->write("_uniforms");
1396 separator = ", ";
1397 }
1398 if (requirements & kGlobals_Requirement) {
1399 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001400 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001401 separator = ", ";
1402 }
1403 if (requirements & kFragCoord_Requirement) {
1404 this->write(separator);
1405 this->write("_fragCoord");
1406 separator = ", ";
1407 }
1408}
1409
1410void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1411 const char*& separator) {
1412 Requirements requirements = this->requirements(f);
1413 if (requirements & kInputs_Requirement) {
1414 this->write(separator);
1415 this->write("Inputs _in");
1416 separator = ", ";
1417 }
1418 if (requirements & kOutputs_Requirement) {
1419 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001420 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001421 separator = ", ";
1422 }
1423 if (requirements & kUniforms_Requirement) {
1424 this->write(separator);
1425 this->write("Uniforms _uniforms");
1426 separator = ", ";
1427 }
1428 if (requirements & kGlobals_Requirement) {
1429 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001430 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001431 separator = ", ";
1432 }
1433 if (requirements & kFragCoord_Requirement) {
1434 this->write(separator);
1435 this->write("float4 _fragCoord");
1436 separator = ", ";
1437 }
1438}
1439
John Stilesda5cdf62021-01-28 11:47:29 -05001440int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1441 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
1442 : fProgram.fSettings.fDefaultUniformBinding;
1443}
1444
1445int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1446 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
1447 : fProgram.fSettings.fDefaultUniformSet;
1448}
1449
John Stiles569249b2020-11-03 12:18:22 -05001450bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
John Stilesf7410bd2021-01-19 13:07:55 -05001451 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals._anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001452 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001453 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001454 switch (fProgram.fKind) {
1455 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001456 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001457 break;
1458 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001459 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001460 break;
1461 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001462 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001463 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001464 }
1465 this->write("(Inputs _in [[stage_in]]");
1466 if (-1 != fUniformBuffer) {
1467 this->write(", constant Uniforms& _uniforms [[buffer(" +
1468 to_string(fUniformBuffer) + ")]]");
1469 }
Brian Osman133724c2020-10-28 14:14:39 -04001470 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001471 if (e->is<GlobalVarDeclaration>()) {
1472 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001473 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1474 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1475 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001476 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001477 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001478 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001479 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001480 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001481 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001482 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001483 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001484 }
1485 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001486 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001487 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001488 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001489 this->write(")]]");
1490 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001491 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001492 this->write(SAMPLER_SUFFIX);
1493 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001494 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001495 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001496 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001497 } else if (e->is<InterfaceBlock>()) {
1498 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001499 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001500 continue;
1501 }
1502 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001503 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001504 this->write("& " );
1505 this->write(fInterfaceBlockNameMap[&intf]);
1506 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001507 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001508 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001509 }
1510 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001511 if (fProgram.fKind == Program::kFragment_Kind) {
1512 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001513 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001514 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001515 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001516 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001517 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001518 } else if (fProgram.fKind == Program::kVertex_Kind) {
1519 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001520 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001521 separator = ", ";
1522 } else {
John Stilesb4418502021-02-04 10:57:08 -05001523 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001524 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001525 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001526 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001527 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001528 }
John Stiles569249b2020-11-03 12:18:22 -05001529 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001530 this->write(separator);
1531 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001532 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001533 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001534 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001535 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001536 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001537 }
Timothy Liang651286f2018-06-07 09:55:33 -04001538 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001539 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001540 }
John Stiles569249b2020-11-03 12:18:22 -05001541 this->write(")");
1542 return true;
1543}
Ethan Nicholascc305772017-10-13 16:17:45 -04001544
John Stiles569249b2020-11-03 12:18:22 -05001545void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1546 this->writeFunctionDeclaration(f.declaration());
1547 this->writeLine(";");
1548}
1549
John Stiles986c7fb2020-12-01 14:44:56 -05001550static bool is_block_ending_with_return(const Statement* stmt) {
1551 // This function detects (potentially nested) blocks that end in a return statement.
1552 if (!stmt->is<Block>()) {
1553 return false;
1554 }
1555 const StatementArray& block = stmt->as<Block>().children();
1556 for (int index = block.count(); index--; ) {
1557 const Statement& stmt = *block[index];
1558 if (stmt.is<ReturnStatement>()) {
1559 return true;
1560 }
1561 if (stmt.is<Block>()) {
1562 return is_block_ending_with_return(&stmt);
1563 }
1564 if (!stmt.is<Nop>()) {
1565 break;
1566 }
1567 }
1568 return false;
1569}
1570
John Stiles569249b2020-11-03 12:18:22 -05001571void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001572 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001573
John Stiles569249b2020-11-03 12:18:22 -05001574 if (!this->writeFunctionDeclaration(f.declaration())) {
1575 return;
1576 }
1577
John Stiles986c7fb2020-12-01 14:44:56 -05001578 fCurrentFunction = &f.declaration();
1579 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1580
John Stiles569249b2020-11-03 12:18:22 -05001581 this->writeLine(" {");
1582
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001583 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001584 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001585 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001586 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001587 }
John Stilesc67b3622020-05-28 17:53:13 -04001588
Ethan Nicholascc305772017-10-13 16:17:45 -04001589 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001590 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001591 {
1592 AutoOutputStream outputToBuffer(this, &buffer);
1593 fIndentation++;
1594 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1595 if (!stmt->isEmpty()) {
1596 this->writeStatement(*stmt);
1597 this->writeLine();
1598 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001599 }
John Stiles44532372020-12-07 12:33:55 -05001600 if (f.declaration().name() == "main") {
1601 // If the main function doesn't end with a return, we need to synthesize one here.
1602 if (!is_block_ending_with_return(f.body().get())) {
1603 this->writeReturnStatementFromMain();
1604 this->writeLine("");
1605 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001606 }
John Stiles44532372020-12-07 12:33:55 -05001607 fIndentation--;
1608 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001609 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001610 this->write(fFunctionHeader);
1611 this->write(buffer.str());
1612}
1613
1614void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001615 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001616 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1617 this->write("thread ");
1618 }
1619 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001620 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001621 }
1622}
1623
1624void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001625 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001626 return;
1627 }
John Stiles06b84ef2020-12-09 12:35:48 -05001628 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001629 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001630 this->writeLine(intf.typeName() + " {");
1631 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001632 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001633 structType = &structType->componentType();
1634 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001635 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001636 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001637 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001638 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001639 }
1640 fIndentation--;
1641 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001642 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001643 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001644 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001645 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001646 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001647 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001648 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001649 } else if (intf.arraySize() == Type::kUnsizedArray){
1650 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001651 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001652 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001653 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001654 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001655 }
1656 this->writeLine(";");
1657}
1658
Timothy Liangdc89f192018-06-13 09:20:31 -04001659void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1660 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001661 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001662 int currentOffset = 0;
1663 for (const auto& field: fields) {
1664 int fieldOffset = field.fModifiers.fLayout.fOffset;
1665 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001666 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001667 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1668 return;
1669 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001670 if (fieldOffset != -1) {
1671 if (currentOffset > fieldOffset) {
1672 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001673 "offset of field '" + field.fName + "' must be at least " +
1674 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001675 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001676 } else if (currentOffset < fieldOffset) {
1677 this->write("char pad");
1678 this->write(to_string(fPaddingCount++));
1679 this->write("[");
1680 this->write(to_string(fieldOffset - currentOffset));
1681 this->writeLine("];");
1682 currentOffset = fieldOffset;
1683 }
1684 int alignment = memoryLayout.alignment(*fieldType);
1685 if (fieldOffset % alignment) {
1686 fErrors.error(parentOffset,
1687 "offset of field '" + field.fName + "' must be a multiple of " +
1688 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001689 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001690 }
1691 }
Brian Osman8609a242020-09-08 14:01:49 -04001692 size_t fieldSize = memoryLayout.size(*fieldType);
1693 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1694 fErrors.error(parentOffset, "field offset overflow");
1695 return;
1696 }
1697 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001698 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stilesb4418502021-02-04 10:57:08 -05001699 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001700 this->write(" ");
1701 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001702 this->writeLine(";");
1703 if (parentIntf) {
1704 fInterfaceBlockMap[&field] = parentIntf;
1705 }
1706 }
1707}
1708
Ethan Nicholascc305772017-10-13 16:17:45 -04001709void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001710 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001711}
1712
Timothy Liang651286f2018-06-07 09:55:33 -04001713void MetalCodeGenerator::writeName(const String& name) {
1714 if (fReservedWords.find(name) != fReservedWords.end()) {
1715 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1716 }
1717 this->write(name);
1718}
1719
John Stilesb4418502021-02-04 10:57:08 -05001720void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl, bool global) {
1721 if (global && !(varDecl.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001722 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001723 }
John Stilesb4418502021-02-04 10:57:08 -05001724 this->writeModifiers(varDecl.var().modifiers(), global);
1725 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001726 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001727 this->writeName(varDecl.var().name());
1728 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001729 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001730 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001731 }
1732 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001733}
1734
1735void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001736 switch (s.kind()) {
1737 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001738 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001739 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001740 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001741 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001742 this->write(";");
1743 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001744 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001745 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001746 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001747 case Statement::Kind::kVarDeclaration:
1748 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001749 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001750 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001751 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001752 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001753 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001754 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001755 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001756 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001757 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001758 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001759 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001760 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001761 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001762 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001763 this->write("break;");
1764 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001765 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 this->write("continue;");
1767 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001768 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001769 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001770 break;
John Stiles98c1f822020-09-09 14:18:53 -04001771 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001772 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001773 this->write(";");
1774 break;
1775 default:
John Stileseada7bc2021-02-02 16:29:32 -05001776 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001777 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001778 }
1779}
1780
Ethan Nicholascc305772017-10-13 16:17:45 -04001781void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001782 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1783 // something here to make the code valid).
1784 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001785 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001786 this->writeLine("{");
1787 fIndentation++;
1788 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001789 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1790 if (!stmt->isEmpty()) {
1791 this->writeStatement(*stmt);
1792 this->writeLine();
1793 }
1794 }
1795 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001796 fIndentation--;
1797 this->write("}");
1798 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001799}
1800
1801void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1802 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001803 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001804 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001805 this->writeStatement(*stmt.ifTrue());
1806 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001807 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001808 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001809 }
1810}
1811
1812void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001813 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1814 if (!f.initializer() && f.test() && !f.next()) {
1815 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05001816 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05001817 this->write(") ");
1818 this->writeStatement(*f.statement());
1819 return;
1820 }
1821
Ethan Nicholascc305772017-10-13 16:17:45 -04001822 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001823 if (f.initializer() && !f.initializer()->isEmpty()) {
1824 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001825 } else {
1826 this->write("; ");
1827 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001828 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05001829 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001830 }
1831 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001832 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05001833 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001834 }
1835 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001836 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001837}
1838
Ethan Nicholascc305772017-10-13 16:17:45 -04001839void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1840 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001841 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001842 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05001843 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001844 this->write(");");
1845}
1846
1847void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1848 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05001849 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001850 this->writeLine(") {");
1851 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001852 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1853 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001854 this->write("case ");
Brian Osman00185012021-02-04 16:07:11 -05001855 this->writeExpression(*c->value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001856 this->writeLine(":");
1857 } else {
1858 this->writeLine("default:");
1859 }
1860 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001861 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001862 this->writeStatement(*stmt);
1863 this->writeLine();
1864 }
1865 fIndentation--;
1866 }
1867 fIndentation--;
1868 this->write("}");
1869}
1870
John Stiles986c7fb2020-12-01 14:44:56 -05001871void MetalCodeGenerator::writeReturnStatementFromMain() {
1872 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
1873 switch (fProgram.fKind) {
1874 case Program::kFragment_Kind:
John Stilesf7410bd2021-01-19 13:07:55 -05001875 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05001876 break;
1877 case Program::kVertex_Kind:
John Stilesf7410bd2021-01-19 13:07:55 -05001878 this->write("return (_out.sk_Position.y = -_out.sk_Position.y, _out);");
John Stiles986c7fb2020-12-01 14:44:56 -05001879 break;
1880 default:
1881 SkDEBUGFAIL("unsupported kind of program");
1882 }
1883}
1884
Ethan Nicholascc305772017-10-13 16:17:45 -04001885void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stiles986c7fb2020-12-01 14:44:56 -05001886 if (fCurrentFunction && fCurrentFunction->name() == "main") {
1887 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05001888 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
1889 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05001890 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05001891 this->writeLine(";");
1892 } else {
1893 fErrors.error(r.fOffset, "Metal does not support returning '" +
1894 r.expression()->type().description() + "' from main()");
1895 }
John Stiles986c7fb2020-12-01 14:44:56 -05001896 }
1897 this->writeReturnStatementFromMain();
1898 return;
1899 }
1900
Ethan Nicholascc305772017-10-13 16:17:45 -04001901 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001902 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001903 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05001904 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001905 }
1906 this->write(";");
1907}
1908
1909void MetalCodeGenerator::writeHeader() {
1910 this->write("#include <metal_stdlib>\n");
1911 this->write("#include <simd/simd.h>\n");
1912 this->write("using namespace metal;\n");
1913}
1914
1915void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001916 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001917 if (e->is<GlobalVarDeclaration>()) {
1918 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001919 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001920 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001921 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05001922 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05001923 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04001924 if (-1 == fUniformBuffer) {
1925 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05001926 fUniformBuffer = uniformSet;
1927 } else if (uniformSet != fUniformBuffer) {
1928 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1929 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04001930 }
1931 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001932 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001933 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001934 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001935 this->write(";\n");
1936 }
1937 }
1938 }
1939 if (-1 != fUniformBuffer) {
1940 this->write("};\n");
1941 }
1942}
1943
1944void MetalCodeGenerator::writeInputStruct() {
1945 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001946 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001947 if (e->is<GlobalVarDeclaration>()) {
1948 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001949 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001950 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1951 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001952 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001953 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001954 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001955 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001956 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001957 if (fProgram.fKind == Program::kVertex_Kind) {
1958 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001959 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001960 } else if (fProgram.fKind == Program::kFragment_Kind) {
1961 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001962 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001963 }
1964 }
1965 this->write(";\n");
1966 }
1967 }
1968 }
1969 this->write("};\n");
1970}
1971
1972void MetalCodeGenerator::writeOutputStruct() {
1973 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001974 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001975 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001976 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001977 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001978 }
Brian Osman133724c2020-10-28 14:14:39 -04001979 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001980 if (e->is<GlobalVarDeclaration>()) {
1981 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001982 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001983 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1984 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001985 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001986 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001987 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001988 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05001989
1990 int location = var.modifiers().fLayout.fLocation;
1991 if (location < 0) {
1992 fErrors.error(var.fOffset,
1993 "Metal out variables must have 'layout(location=...)'");
1994 } else if (fProgram.fKind == Program::kVertex_Kind) {
1995 this->write(" [[user(locn" + to_string(location) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001996 } else if (fProgram.fKind == Program::kFragment_Kind) {
John Stiles842b3592020-12-01 10:36:37 -05001997 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001998 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001999 if (colorIndex) {
2000 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002001 }
Brian Osmanc0213602020-10-06 14:43:32 -04002002 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002003 }
2004 this->write(";\n");
2005 }
2006 }
Timothy Liang7d637782018-06-05 09:58:07 -04002007 }
2008 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002009 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002010 }
2011 this->write("};\n");
2012}
2013
2014void MetalCodeGenerator::writeInterfaceBlocks() {
2015 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002016 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002017 if (e->is<InterfaceBlock>()) {
2018 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002019 wroteInterfaceBlock = true;
2020 }
2021 }
Jim Van Verth3d482992019-02-07 10:48:05 -05002022 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04002023 this->writeLine("struct sksl_synthetic_uniforms {");
2024 this->writeLine(" float u_skRTHeight;");
2025 this->writeLine("};");
2026 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002027}
2028
John Stilesdc75a972020-11-25 16:24:55 -05002029void MetalCodeGenerator::writeStructDefinitions() {
2030 for (const ProgramElement* e : fProgram.elements()) {
2031 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002032 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002033 }
2034 }
2035}
2036
John Stilescdcdb042020-07-06 09:03:51 -04002037void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2038 // Visit the interface blocks.
2039 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002040 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002041 }
Brian Osman133724c2020-10-28 14:14:39 -04002042 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002043 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002044 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002045 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002046 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2047 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2048 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002049 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04002050 var.type().typeKind() == Type::TypeKind::kSampler) {
2051 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2052 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002053 visitor->visitTexture(var.type(), var.name());
2054 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04002055 } else {
2056 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002057 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002058 }
2059 }
2060 }
John Stilescdcdb042020-07-06 09:03:51 -04002061}
2062
2063void MetalCodeGenerator::writeGlobalStruct() {
2064 class : public GlobalStructVisitor {
2065 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002066 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002067 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002068 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002069 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002070 fCodeGen->write("* ");
2071 fCodeGen->writeName(blockName);
2072 fCodeGen->write(";\n");
2073 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002074 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002075 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002076 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002077 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002078 fCodeGen->write(" ");
2079 fCodeGen->writeName(name);
2080 fCodeGen->write(";\n");
2081 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002082 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002083 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002084 fCodeGen->write(" sampler ");
2085 fCodeGen->writeName(name);
2086 fCodeGen->write(";\n");
2087 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002088 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002089 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002090 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002091 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002092 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002093 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002094 fCodeGen->write(";\n");
2095 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002096 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002097 if (fFirst) {
2098 fCodeGen->write("struct Globals {\n");
2099 fFirst = false;
2100 }
2101 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002102 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002103 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002104 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002105 fFirst = true;
2106 }
2107 }
2108
2109 MetalCodeGenerator* fCodeGen = nullptr;
2110 bool fFirst = true;
2111 } visitor;
2112
2113 visitor.fCodeGen = this;
2114 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002115 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002116}
2117
2118void MetalCodeGenerator::writeGlobalInit() {
2119 class : public GlobalStructVisitor {
2120 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002121 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002122 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002123 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002124 fCodeGen->write("&");
2125 fCodeGen->writeName(blockName);
2126 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002127 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002128 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002129 fCodeGen->writeName(name);
2130 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002131 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002132 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002133 fCodeGen->writeName(name);
2134 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002135 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002136 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002137 if (value) {
2138 fCodeGen->writeVarInitializer(var, *value);
2139 } else {
2140 fCodeGen->write("{}");
2141 }
2142 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002143 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002144 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002145 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002146 fFirst = false;
2147 } else {
2148 fCodeGen->write(", ");
2149 }
2150 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002151 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002152 if (!fFirst) {
2153 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002154 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002155 }
2156 }
2157 MetalCodeGenerator* fCodeGen = nullptr;
2158 bool fFirst = true;
2159 } visitor;
2160
2161 visitor.fCodeGen = this;
2162 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002163 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002164}
2165
Ethan Nicholascc305772017-10-13 16:17:45 -04002166void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002167 switch (e.kind()) {
2168 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002169 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002170 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002171 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2172 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2173 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002174 if (-1 == builtin) {
2175 // normal var
2176 this->writeVarDeclaration(decl, true);
2177 this->writeLine();
2178 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2179 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002180 }
2181 break;
2182 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002183 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002184 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002185 break;
John Stilesdc75a972020-11-25 16:24:55 -05002186 case ProgramElement::Kind::kStructDefinition:
2187 // Handled in writeStructDefinitions. Do nothing.
2188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002189 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002190 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002191 break;
John Stiles569249b2020-11-03 12:18:22 -05002192 case ProgramElement::Kind::kFunctionPrototype:
2193 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002195 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002196 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2197 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002198 this->writeLine(";");
2199 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002200 case ProgramElement::Kind::kEnum:
2201 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002202 default:
John Stileseada7bc2021-02-02 16:29:32 -05002203 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002204 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002205 }
2206}
2207
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002208MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2209 if (!e) {
2210 return kNo_Requirements;
2211 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002212 switch (e->kind()) {
2213 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002214 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002215 Requirements result = this->requirements(f.function());
2216 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002217 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002218 }
2219 return result;
2220 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002221 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002222 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04002223 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002224 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002225 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002226 }
2227 return result;
2228 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002229 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002230 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002231 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002232 return kGlobals_Requirement;
2233 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002234 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002235 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002236 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002237 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002238 case Expression::Kind::kBinary: {
2239 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002240 return this->requirements(bin.left().get()) |
2241 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002242 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002243 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002244 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002245 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002246 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002247 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002248 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002249 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002250 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002251 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002252 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002253 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2254 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002255 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002256 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002257 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002258 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002259 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002260 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002261 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002262 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002263 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002264 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002265 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002266 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002267 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002268 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002269 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002270 } else {
2271 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002272 }
2273 }
2274 return result;
2275 }
2276 default:
2277 return kNo_Requirements;
2278 }
2279}
2280
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002281MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2282 if (!s) {
2283 return kNo_Requirements;
2284 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002285 switch (s->kind()) {
2286 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002287 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002288 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002289 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002290 }
2291 return result;
2292 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002293 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002294 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002295 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002296 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002297 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002298 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002299 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002300 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002301 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002302 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002303 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002304 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002305 return this->requirements(i.test().get()) |
2306 this->requirements(i.ifTrue().get()) |
2307 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002308 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002309 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002310 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002311 return this->requirements(f.initializer().get()) |
2312 this->requirements(f.test().get()) |
2313 this->requirements(f.next().get()) |
2314 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002315 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002316 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002317 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002318 return this->requirements(d.test().get()) |
2319 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002320 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002321 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002322 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002323 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04002324 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
2325 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002326 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002327 }
2328 }
2329 return result;
2330 }
2331 default:
2332 return kNo_Requirements;
2333 }
2334}
2335
2336MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002337 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002338 return kNo_Requirements;
2339 }
2340 auto found = fRequirements.find(&f);
2341 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002342 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002343 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002344 if (e->is<FunctionDefinition>()) {
2345 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002346 if (&def.declaration() == &f) {
2347 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002348 fRequirements[&f] = reqs;
2349 return reqs;
2350 }
2351 }
2352 }
John Stiles569249b2020-11-03 12:18:22 -05002353 // We never found a definition for this declared function, but it's legal to prototype a
2354 // function without ever giving a definition, as long as you don't call it.
2355 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002356 }
2357 return found->second;
2358}
2359
Timothy Liangb8eeb802018-07-23 16:46:16 -04002360bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04002361 fProgramKind = fProgram.fKind;
Ethan Nicholascc305772017-10-13 16:17:45 -04002362
John Stiles44532372020-12-07 12:33:55 -05002363 StringStream header;
2364 {
2365 AutoOutputStream outputToHeader(this, &header, &fIndentation);
2366 this->writeHeader();
2367 this->writeStructDefinitions();
2368 this->writeUniformStruct();
2369 this->writeInputStruct();
2370 this->writeOutputStruct();
2371 this->writeInterfaceBlocks();
2372 this->writeGlobalStruct();
2373 }
2374 StringStream body;
2375 {
2376 AutoOutputStream outputToBody(this, &body, &fIndentation);
2377 for (const ProgramElement* e : fProgram.elements()) {
2378 this->writeProgramElement(*e);
2379 }
2380 }
2381 write_stringstream(header, *fOut);
2382 write_stringstream(fExtraFunctions, *fOut);
2383 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002384 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002385}
2386
John Stilesa6841be2020-08-06 14:11:56 -04002387} // namespace SkSL