blob: 5d1ba3e9dcc7d2deffa9997042294d26525905bc [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 "!=";
28 default: return Compiler::OperatorName(op);
29 }
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() {
Timothy Liang7d637782018-06-05 09:58:07 -040042#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
43#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
John Stiles0063a9f2020-12-10 18:01:45 -050044 fIntrinsicMap[String("floatBitsToInt")] = SPECIAL(Bitcast);
45 fIntrinsicMap[String("floatBitsToUint")] = SPECIAL(Bitcast);
46 fIntrinsicMap[String("intBitsToFloat")] = SPECIAL(Bitcast);
47 fIntrinsicMap[String("uintBitsToFloat")] = SPECIAL(Bitcast);
John Stilese2d34f82020-12-10 18:02:02 -050048 fIntrinsicMap[String("degrees")] = SPECIAL(Degrees);
Brian Osman46787d52020-11-24 14:18:23 -050049 fIntrinsicMap[String("distance")] = SPECIAL(Distance);
50 fIntrinsicMap[String("dot")] = SPECIAL(Dot);
John Stilesad0571f2020-12-10 18:03:10 -050051 fIntrinsicMap[String("faceforward")] = SPECIAL(Faceforward);
John Stilese7dc7cb2020-12-22 15:37:14 -050052 fIntrinsicMap[String("bitCount")] = SPECIAL(BitCount);
John Stiles86424eb2020-12-11 11:17:14 -050053 fIntrinsicMap[String("findLSB")] = SPECIAL(FindLSB);
John Stiles9685e522020-12-14 11:52:14 -050054 fIntrinsicMap[String("findMSB")] = SPECIAL(FindMSB);
Brian Osman46787d52020-11-24 14:18:23 -050055 fIntrinsicMap[String("length")] = SPECIAL(Length);
Timothy Liang651286f2018-06-07 09:55:33 -040056 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Brian Osman46787d52020-11-24 14:18:23 -050057 fIntrinsicMap[String("normalize")] = SPECIAL(Normalize);
John Stilese2d34f82020-12-10 18:02:02 -050058 fIntrinsicMap[String("radians")] = SPECIAL(Radians);
Brian Osman46787d52020-11-24 14:18:23 -050059 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050060 fIntrinsicMap[String("equal")] = METAL(Equal);
61 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040062 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
63 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
64 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
65 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040066}
67
Ethan Nicholascc305772017-10-13 16:17:45 -040068void MetalCodeGenerator::write(const char* s) {
69 if (!s[0]) {
70 return;
71 }
72 if (fAtLineStart) {
73 for (int i = 0; i < fIndentation; i++) {
74 fOut->writeText(" ");
75 }
76 }
77 fOut->writeText(s);
78 fAtLineStart = false;
79}
80
81void MetalCodeGenerator::writeLine(const char* s) {
82 this->write(s);
83 fOut->writeText(fLineEnding);
84 fAtLineStart = true;
85}
86
87void MetalCodeGenerator::write(const String& s) {
88 this->write(s.c_str());
89}
90
91void MetalCodeGenerator::writeLine(const String& s) {
92 this->writeLine(s.c_str());
93}
94
95void MetalCodeGenerator::writeLine() {
96 this->writeLine("");
97}
98
99void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -0400100 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -0400101}
102
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500103String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400104 switch (type.typeKind()) {
105 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500106 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -0400107 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500108 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
109 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -0400110 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -0500111 return "texture2d<float>"; // FIXME - support other texture types
John Stilesfd41d872020-11-25 22:39:45 -0500112 case Type::TypeKind::kEnum:
113 return "int";
Ethan Nicholascc305772017-10-13 16:17:45 -0400114 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400115 if (type == *fContext.fHalf_Type) {
116 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500117 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -0400118 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500119 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -0400120 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500121 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400122 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500123 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400124 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400125 }
126}
127
John Stilesdc75a972020-11-25 16:24:55 -0500128bool MetalCodeGenerator::writeStructDefinition(const Type& type) {
129 for (const Type* search : fWrittenStructs) {
130 if (*search == type) {
131 // already written
132 return false;
133 }
134 }
135 fWrittenStructs.push_back(&type);
136 this->writeLine("struct " + type.name() + " {");
137 fIndentation++;
138 this->writeFields(type.fields(), type.fOffset);
139 fIndentation--;
140 this->write("}");
141 return true;
142}
143
John Stiles3dba3ee2020-12-02 23:35:49 -0500144// Flags an error if an array type is found. Meant to be used in places where an array type might
145// appear in the SkSL/IR, but can't be represented by Metal.
John Stilesea166702020-12-11 17:30:47 -0500146void MetalCodeGenerator::disallowArrayTypes(const Type& type, int offset) {
John Stilesc0c51062020-12-03 17:16:29 -0500147 if (type.isArray()) {
John Stilesea166702020-12-11 17:30:47 -0500148 fErrors.error(offset, "Metal does not support array types in this context");
John Stiles3dba3ee2020-12-02 23:35:49 -0500149 }
150}
151
152// Writes the base type, stripping array suffixes. e.g. `float[2]` will output `float`.
153// Call `writeArrayDimensions` to write the type's accompanying array sizes.
154void MetalCodeGenerator::writeBaseType(const Type& type) {
155 switch (type.typeKind()) {
156 case Type::TypeKind::kStruct:
157 if (!this->writeStructDefinition(type)) {
158 this->write(type.name());
159 }
160 break;
161 case Type::TypeKind::kArray:
162 this->writeBaseType(type.componentType());
163 break;
164 default:
165 this->write(this->typeName(type));
166 break;
167 }
168}
169
170// Writes the array suffix of a type, if one exists. e.g. `float[2][4]` will output `[2][4]`.
171void MetalCodeGenerator::writeArrayDimensions(const Type& type) {
John Stilesc0c51062020-12-03 17:16:29 -0500172 if (type.isArray()) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500173 this->write("[");
174 if (type.columns() != Type::kUnsizedArray) {
175 this->write(to_string(type.columns()));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500176 }
John Stiles3dba3ee2020-12-02 23:35:49 -0500177 this->write("]");
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500178 }
179}
180
Ethan Nicholascc305772017-10-13 16:17:45 -0400181void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400182 switch (expr.kind()) {
183 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400184 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400185 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400186 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400187 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400189 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400190 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400192 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400193 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400196 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400199 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400200 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400201 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400202 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400203 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400204 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400205 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400206 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400207 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400208 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400209 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400210 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400211 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400212 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400213 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400214 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400215 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400216 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400217 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400218 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400219 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400220 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400221 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400222 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400223 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400224 break;
225 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500226#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400227 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500228#endif
229 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400230 }
231}
232
Timothy Liang6403b0e2018-05-17 10:40:04 -0400233void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400234 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400235 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400236 Intrinsic intrinsic = i->second;
237 int32_t intrinsicId = intrinsic.second;
238 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400239 case kSpecial_IntrinsicKind:
240 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400241 break;
242 case kMetal_IntrinsicKind:
John Stiles47b4b192020-12-08 18:08:11 -0500243 this->write("(");
244 this->writeExpression(*c.arguments()[0], kRelational_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400245 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500246 case kEqual_MetalIntrinsic:
247 this->write(" == ");
248 break;
249 case kNotEqual_MetalIntrinsic:
250 this->write(" != ");
251 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400252 case kLessThan_MetalIntrinsic:
253 this->write(" < ");
254 break;
255 case kLessThanEqual_MetalIntrinsic:
256 this->write(" <= ");
257 break;
258 case kGreaterThan_MetalIntrinsic:
259 this->write(" > ");
260 break;
261 case kGreaterThanEqual_MetalIntrinsic:
262 this->write(" >= ");
263 break;
264 default:
John Stiles47b4b192020-12-08 18:08:11 -0500265 ABORT("unsupported Metal intrinsic kind");
Timothy Lianga06f2152018-05-24 15:33:31 -0400266 }
John Stiles47b4b192020-12-08 18:08:11 -0500267 this->writeExpression(*c.arguments()[1], kRelational_Precedence);
268 this->write(")");
Timothy Lianga06f2152018-05-24 15:33:31 -0400269 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400270 default:
271 ABORT("unsupported intrinsic kind");
272 }
273}
274
John Stiles06b84ef2020-12-09 12:35:48 -0500275String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
276 const ExpressionArray& arguments,
277 const SkTArray<VariableReference*>& outVars) {
278 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
279 const FunctionDeclaration& function = call.function();
280
281 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) + "_" + function.name();
282 const char* separator = "";
283
284 // Emit a prototype for the function we'll be calling through to in our helper.
285 if (!function.isBuiltin()) {
286 this->writeFunctionDeclaration(function);
287 this->writeLine(";");
288 }
289
290 // Synthesize a helper function that takes the same inputs as `function`, except in places where
291 // `outVars` is non-null; in those places, we take the type of the VariableReference.
292 //
293 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
294 this->writeBaseType(call.type());
295 this->write(" ");
296 this->write(name);
297 this->write("(");
298 this->writeFunctionRequirementParams(function, separator);
299
300 SkASSERT(outVars.size() == arguments.size());
301 SkASSERT(outVars.size() == function.parameters().size());
302
303 for (int index = 0; index < arguments.count(); ++index) {
304 this->write(separator);
305 separator = ", ";
306
307 const Variable* param = function.parameters()[index];
308 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
309
310 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
311 this->writeBaseType(*type);
312
313 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
314 this->write("&");
315 }
316 if (outVars[index]) {
317 this->write(" ");
318 fIgnoreVariableReferenceModifiers = true;
319 this->writeVariableReference(*outVars[index]);
320 fIgnoreVariableReferenceModifiers = false;
321 } else {
322 this->write(" _var");
323 this->write(to_string(index));
324 }
325 this->writeArrayDimensions(*type);
326 }
327 this->writeLine(") {");
328
329 ++fIndentation;
330 for (int index = 0; index < outVars.count(); ++index) {
331 if (!outVars[index]) {
332 continue;
333 }
334 // float3 _var2[ = outParam.zyx];
335 this->writeBaseType(arguments[index]->type());
336 this->write(" _var");
337 this->write(to_string(index));
338
339 const Variable* param = function.parameters()[index];
340 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
341 this->write(" = ");
342 fIgnoreVariableReferenceModifiers = true;
343 this->writeExpression(*arguments[index], kAssignment_Precedence);
344 fIgnoreVariableReferenceModifiers = false;
345 }
346
347 this->writeLine(";");
348 }
349
350 // [int _skResult = ] myFunction(inputs, outputs, globals, _var0, _var1, _var2, _var3);
351 bool hasResult = (call.type().name() != "void");
352 if (hasResult) {
353 this->writeBaseType(call.type());
354 this->write(" _skResult = ");
355 }
356
357 this->writeName(function.name());
358 this->write("(");
359 separator = "";
360 this->writeFunctionRequirementArgs(function, separator);
361
362 for (int index = 0; index < arguments.count(); ++index) {
363 this->write(separator);
364 separator = ", ";
365
366 this->write("_var");
367 this->write(to_string(index));
368 }
369 this->writeLine(");");
370
371 for (int index = 0; index < outVars.count(); ++index) {
372 if (!outVars[index]) {
373 continue;
374 }
375 // outParam.zyx = _var2;
376 fIgnoreVariableReferenceModifiers = true;
377 this->writeExpression(*arguments[index], kAssignment_Precedence);
378 fIgnoreVariableReferenceModifiers = false;
379 this->write(" = _var");
380 this->write(to_string(index));
381 this->writeLine(";");
382 }
383
384 if (hasResult) {
385 this->writeLine("return _skResult;");
386 }
387
388 --fIndentation;
389 this->writeLine("}");
390
391 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500392}
393
John Stilesf64e4072020-12-10 10:34:27 -0500394String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
395 return "as_type<" + outType.displayName() + ">";
396}
397
Ethan Nicholascc305772017-10-13 16:17:45 -0400398void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400399 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400400 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400401 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400402 if (entry != fIntrinsicMap.end()) {
403 this->writeIntrinsicCall(c);
404 return;
405 }
John Stilesb21fac22020-12-04 15:36:49 -0500406 String name = function.name();
John Stilesb21fac22020-12-04 15:36:49 -0500407
John Stilesf64e4072020-12-10 10:34:27 -0500408 if (function.isBuiltin()) {
409 if (name == "atan" && arguments.size() == 2) {
410 name = "atan2";
411 } else if (name == "inversesqrt") {
412 name = "rsqrt";
413 } else if (name == "inverse") {
414 SkASSERT(arguments.size() == 1);
415 name = this->getInverseHack(*arguments[0]);
416 } else if (name == "dFdx") {
417 name = "dfdx";
418 } else if (name == "dFdy") {
419 // Flipping Y also negates the Y derivatives.
420 if (fProgram.fSettings.fFlipY) {
421 this->write("-");
422 }
423 name = "dfdy";
John Stilesb21fac22020-12-04 15:36:49 -0500424 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400425 }
John Stilesb21fac22020-12-04 15:36:49 -0500426
John Stilesf64e4072020-12-10 10:34:27 -0500427 // We emulate GLSL's out-param semantics for Metal using a helper function. (Specifically,
428 // results are only written back to the original variable at the end of the function call; also,
429 // swizzles are supported, whereas Metal doesn't allow a swizzle to be passed to a `floatN&`.)
John Stilesb21fac22020-12-04 15:36:49 -0500430 const std::vector<const Variable*>& parameters = function.parameters();
431 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500432
433 bool foundOutParam = false;
434 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500435 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500436
437 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500438 // If this is an out parameter...
439 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500440 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500441 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500442 // Assignability was verified at IRGeneration time, so this should always succeed.
443 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
444 outVars[index] = info.fAssignedVar;
445 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500446 }
447 }
448
John Stiles06b84ef2020-12-09 12:35:48 -0500449 if (foundOutParam) {
450 // Out parameters need to be written back to at the end of the function. To do this, we
451 // synthesize a helper function which evaluates the out-param expression into a temporary
452 // variable, calls the original function, then writes the temp var back into the out param
453 // using the original out-param expression. (This lets us support things like swizzles and
454 // array indices.)
455 name = getOutParamHelper(c, arguments, outVars);
456 }
457
John Stilesb21fac22020-12-04 15:36:49 -0500458 this->write(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400459 this->write("(");
460 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500461 this->writeFunctionRequirementArgs(function, separator);
462 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400463 this->write(separator);
464 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500465
466 if (outVars[i]) {
467 this->writeExpression(*outVars[i], kSequence_Precedence);
468 } else {
469 this->writeExpression(*arguments[i], kSequence_Precedence);
470 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400471 }
472 this->write(")");
473}
474
Brian Osman964f0a02020-12-29 10:15:22 -0500475static constexpr char kInverse2x2[] = R"(
476float2x2 float2x2_inverse(float2x2 m) {
477 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
478}
479)";
480
481static constexpr char kInverse3x3[] = R"(
482float3x3 float3x3_inverse(float3x3 m) {
483 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
484 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
485 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
486 float b01 = a22*a11 - a12*a21;
487 float b11 = -a22*a10 + a12*a20;
488 float b21 = a21*a10 - a11*a20;
489 float det = a00*b01 + a01*b11 + a02*b21;
490 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
491 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
492 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
493}
494)";
495
496static constexpr char kInverse4x4[] = R"(
497float4x4 float4x4_inverse(float4x4 m) {
498 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
499 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
500 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
501 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
502 float b00 = a00*a11 - a01*a10;
503 float b01 = a00*a12 - a02*a10;
504 float b02 = a00*a13 - a03*a10;
505 float b03 = a01*a12 - a02*a11;
506 float b04 = a01*a13 - a03*a11;
507 float b05 = a02*a13 - a03*a12;
508 float b06 = a20*a31 - a21*a30;
509 float b07 = a20*a32 - a22*a30;
510 float b08 = a20*a33 - a23*a30;
511 float b09 = a21*a32 - a22*a31;
512 float b10 = a21*a33 - a23*a31;
513 float b11 = a22*a33 - a23*a32;
514 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
515 return float4x4(a11*b11 - a12*b10 + a13*b09,
516 a02*b10 - a01*b11 - a03*b09,
517 a31*b05 - a32*b04 + a33*b03,
518 a22*b04 - a21*b05 - a23*b03,
519 a12*b08 - a10*b11 - a13*b07,
520 a00*b11 - a02*b08 + a03*b07,
521 a32*b02 - a30*b05 - a33*b01,
522 a20*b05 - a22*b02 + a23*b01,
523 a10*b10 - a11*b08 + a13*b06,
524 a01*b08 - a00*b10 - a03*b06,
525 a30*b04 - a31*b02 + a33*b00,
526 a21*b02 - a20*b04 - a23*b00,
527 a11*b07 - a10*b09 - a12*b06,
528 a00*b09 - a01*b07 + a02*b06,
529 a31*b01 - a30*b03 - a32*b00,
530 a20*b03 - a21*b01 + a22*b00) * (1/det);
531}
532)";
533
John Stilesb21fac22020-12-04 15:36:49 -0500534String MetalCodeGenerator::getInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400535 const Type& type = mat.type();
Brian Osman964f0a02020-12-29 10:15:22 -0500536 String name = this->typeName(type) + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400537 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500538 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
539 fWrittenIntrinsics.insert(name);
Brian Osman964f0a02020-12-29 10:15:22 -0500540 fExtraFunctions.writeText(kInverse2x2);
Chris Daltondba7aab2018-11-15 10:57:49 -0500541 }
542 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400543 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500544 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
545 fWrittenIntrinsics.insert(name);
Brian Osman964f0a02020-12-29 10:15:22 -0500546 fExtraFunctions.writeText(kInverse3x3);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500547 }
548 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400549 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500550 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
551 fWrittenIntrinsics.insert(name);
Brian Osman964f0a02020-12-29 10:15:22 -0500552 fExtraFunctions.writeText(kInverse4x4);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500553 }
554 }
John Stilesb21fac22020-12-04 15:36:49 -0500555 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500556}
557
John Stiles86424eb2020-12-11 11:17:14 -0500558String MetalCodeGenerator::getTempVariable(const Type& type) {
559 String tempVar = "_skTemp" + to_string(fVarCount++);
560 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
561 return tempVar;
562}
563
Timothy Liang6403b0e2018-05-17 10:40:04 -0400564void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400565 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400566 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400567 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400568 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400569 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400570 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400571 this->write(SAMPLER_SUFFIX);
572 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400573 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400574 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500575 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500576 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500577 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400578 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500579 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400580 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400581 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400582 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400583 this->write(")");
584 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400585 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400586 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500587 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400588 // 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 -0500589 String tmpX = this->getTempVariable(arguments[0]->type());
590 String tmpY = this->getTempVariable(arguments[0]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500591 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400592 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500593 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400594 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500595 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400596 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500597 }
Brian Osman46787d52020-11-24 14:18:23 -0500598 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
599 case kDistance_SpecialIntrinsic: {
600 if (arguments[0]->type().columns() == 1) {
601 this->write("abs(");
602 this->writeExpression(*arguments[0], kAdditive_Precedence);
603 this->write(" - ");
604 this->writeExpression(*arguments[1], kAdditive_Precedence);
605 this->write(")");
606 } else {
607 this->write("distance(");
608 this->writeExpression(*arguments[0], kSequence_Precedence);
609 this->write(", ");
610 this->writeExpression(*arguments[1], kSequence_Precedence);
611 this->write(")");
612 }
613 break;
614 }
615 case kDot_SpecialIntrinsic: {
616 if (arguments[0]->type().columns() == 1) {
617 this->write("(");
618 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
619 this->write(" * ");
620 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
621 this->write(")");
622 } else {
623 this->write("dot(");
624 this->writeExpression(*arguments[0], kSequence_Precedence);
625 this->write(", ");
626 this->writeExpression(*arguments[1], kSequence_Precedence);
627 this->write(")");
628 }
629 break;
630 }
John Stilesad0571f2020-12-10 18:03:10 -0500631 case kFaceforward_SpecialIntrinsic: {
632 if (arguments[0]->type().columns() == 1) {
633 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
634 this->write("((((");
635 this->writeExpression(*arguments[2], kSequence_Precedence);
636 this->write(") * (");
637 this->writeExpression(*arguments[1], kSequence_Precedence);
638 this->write(") < 0) ? 1 : -1) * (");
639 this->writeExpression(*arguments[0], kSequence_Precedence);
640 this->write("))");
641 } else {
642 this->write("faceforward(");
643 this->writeExpression(*arguments[0], kSequence_Precedence);
644 this->write(", ");
645 this->writeExpression(*arguments[1], kSequence_Precedence);
646 this->write(", ");
647 this->writeExpression(*arguments[2], kSequence_Precedence);
648 this->write(")");
649 }
650 break;
651 }
Brian Osman46787d52020-11-24 14:18:23 -0500652 case kLength_SpecialIntrinsic: {
653 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
654 this->writeExpression(*arguments[0], kSequence_Precedence);
655 this->write(")");
656 break;
657 }
658 case kNormalize_SpecialIntrinsic: {
659 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
660 this->writeExpression(*arguments[0], kSequence_Precedence);
661 this->write(")");
662 break;
663 }
John Stiles0063a9f2020-12-10 18:01:45 -0500664 case kBitcast_SpecialIntrinsic: {
665 this->write(this->getBitcastIntrinsic(c.type()));
666 this->write("(");
667 this->writeExpression(*arguments[0], kSequence_Precedence);
668 this->write(")");
669 break;
670 }
John Stilese2d34f82020-12-10 18:02:02 -0500671 case kDegrees_SpecialIntrinsic: {
672 this->write("((");
673 this->writeExpression(*arguments[0], kSequence_Precedence);
674 this->write(") * 57.2957795)");
675 break;
676 }
677 case kRadians_SpecialIntrinsic: {
678 this->write("((");
679 this->writeExpression(*arguments[0], kSequence_Precedence);
680 this->write(") * 0.0174532925)");
681 break;
682 }
John Stilese7dc7cb2020-12-22 15:37:14 -0500683 case kBitCount_SpecialIntrinsic: {
684 this->write("popcount(");
685 this->writeExpression(*arguments[0], kSequence_Precedence);
686 this->write(")");
687 break;
688 }
John Stiles86424eb2020-12-11 11:17:14 -0500689 case kFindLSB_SpecialIntrinsic: {
690 // Create a temp variable to store the expression, to avoid double-evaluating it.
691 String skTemp = this->getTempVariable(arguments[0]->type());
692 String exprType = this->typeName(arguments[0]->type());
693
694 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
695 // Use select to detect zero inputs and force a -1 result.
696
697 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
698 this->write("(");
699 this->write(skTemp);
700 this->write(" = (");
701 this->writeExpression(*arguments[0], kSequence_Precedence);
702 this->write("), select(ctz(");
703 this->write(skTemp);
704 this->write("), ");
705 this->write(exprType);
706 this->write("(-1), ");
707 this->write(skTemp);
708 this->write(" == ");
709 this->write(exprType);
710 this->write("(0)))");
711 break;
712 }
John Stiles9685e522020-12-14 11:52:14 -0500713 case kFindMSB_SpecialIntrinsic: {
714 // Create a temp variable to store the expression, to avoid double-evaluating it.
715 String skTemp1 = this->getTempVariable(arguments[0]->type());
716 String exprType = this->typeName(arguments[0]->type());
717
718 // GLSL findMSB is actually quite different from Metal's clz:
719 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
720 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
721
722 // (_skTemp1 = (.....),
723 this->write("(");
724 this->write(skTemp1);
725 this->write(" = (");
726 this->writeExpression(*arguments[0], kSequence_Precedence);
727 this->write("), ");
728
729 // Signed input types might be negative; we need another helper variable to negate the
730 // input (since we can only find one bits, not zero bits).
731 String skTemp2;
732 if (arguments[0]->type().isSigned()) {
733 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
734 skTemp2 = this->getTempVariable(arguments[0]->type());
735 this->write(skTemp2);
736 this->write(" = (select(");
737 this->write(skTemp1);
738 this->write(", ~");
739 this->write(skTemp1);
740 this->write(", ");
741 this->write(skTemp1);
742 this->write(" < 0)), ");
743 } else {
744 skTemp2 = skTemp1;
745 }
746
747 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
748 this->write("select(");
749 this->write(this->typeName(c.type()));
750 this->write("(clz(");
751 this->write(skTemp2);
752 this->write(")), ");
753 this->write(this->typeName(c.type()));
754 this->write("(-1), ");
755 this->write(skTemp2);
756 this->write(" == ");
757 this->write(exprType);
758 this->write("(0)))");
759 break;
760 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400761 default:
762 ABORT("unsupported special intrinsic kind");
763 }
764}
765
John Stilesfcf8cb22020-08-06 14:29:22 -0400766// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
767// Cells that don't exist in the source matrix will be populated with identity-matrix values.
768void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
769 SkASSERT(rows <= 4);
770 SkASSERT(columns <= 4);
771
772 const char* columnSeparator = "";
773 for (int c = 0; c < columns; ++c) {
774 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
775 columnSeparator = "), ";
776
777 // Determine how many values to take from the source matrix for this row.
778 int swizzleLength = 0;
779 if (c < sourceMatrix.columns()) {
780 swizzleLength = std::min<>(rows, sourceMatrix.rows());
781 }
782
783 // Emit all the values from the source matrix row.
784 bool firstItem;
785 switch (swizzleLength) {
786 case 0: firstItem = true; break;
787 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
788 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
789 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
790 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
791 default: SkUNREACHABLE;
792 }
793
794 // Emit the placeholder identity-matrix cells.
795 for (int r = swizzleLength; r < rows; ++r) {
796 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
797 firstItem = false;
798 }
799 }
800
801 fExtraFunctions.writeText(")");
802}
803
804// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
805// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400806void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
807 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400808 size_t argIndex = 0;
809 int argPosition = 0;
810
811 const char* columnSeparator = "";
812 for (int c = 0; c < columns; ++c) {
813 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
814 columnSeparator = "), ";
815
816 const char* rowSeparator = "";
817 for (int r = 0; r < rows; ++r) {
818 fExtraFunctions.writeText(rowSeparator);
819 rowSeparator = ", ";
820
821 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400822 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400823 switch (argType.typeKind()) {
824 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400825 fExtraFunctions.printf("x%zu", argIndex);
826 break;
827 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400828 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400829 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
830 break;
831 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400832 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400833 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
834 argPosition / argType.rows(),
835 argPosition % argType.rows());
836 break;
837 }
838 default: {
839 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
840 fExtraFunctions.writeText("<error>");
841 break;
842 }
843 }
844
845 ++argPosition;
846 if (argPosition >= argType.columns() * argType.rows()) {
847 ++argIndex;
848 argPosition = 0;
849 }
850 } else {
851 SkDEBUGFAIL("not enough arguments for matrix constructor");
852 fExtraFunctions.writeText("<error>");
853 }
854 }
855 }
856
857 if (argPosition != 0 || argIndex != args.size()) {
858 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
859 fExtraFunctions.writeText(", <error>");
860 }
861
862 fExtraFunctions.writeText(")");
863}
864
John Stiles1bdafbf2020-05-28 12:17:20 -0400865// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
866// Keeps track of previously generated constructors so that we won't generate more than one
867// constructor for any given permutation of input argument types. Returns the name of the
868// generated constructor method.
869String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400870 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500871 int columns = matrix.columns();
872 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400873 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400874
875 // Create the helper-method name and use it as our lookup key.
876 String name;
877 name.appendf("float%dx%d_from", columns, rows);
878 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500879 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400880 }
881
882 // If a helper-method has already been synthesized, we don't need to synthesize it again.
883 auto [iter, newlyCreated] = fHelpers.insert(name);
884 if (!newlyCreated) {
885 return name;
886 }
887
888 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
889 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
890 // supply a mixture of scalars and vectors.)
891 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
892
893 size_t argIndex = 0;
894 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400895 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400896 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500897 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400898 argSeparator = ", ";
899 }
900
901 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
902
John Stiles9aeed132020-11-24 17:36:06 -0500903 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400904 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400905 } else {
906 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400907 }
908
John Stilesfcf8cb22020-08-06 14:29:22 -0400909 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500910 return name;
911}
912
913bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
914 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
915 return false;
916 }
917 if (t1.columns() > 1) {
918 return this->canCoerce(t1.componentType(), t2.componentType());
919 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500920 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500921}
922
John Stiles1bdafbf2020-05-28 12:17:20 -0400923bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
924 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500925 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400926 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500927 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400928
929 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
930 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
931 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
932 // scalars can be constructed trivially. In more complex cases, we generate a helper function
933 // that converts our inputs into a properly-shaped matrix.
934 // A matrix construct helper method is always used if any input argument is a matrix.
935 // Helper methods are also necessary when any argument would span multiple rows. For instance:
936 //
937 // float2 x = (1, 2);
938 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
939 // | 2 4 6 |
940 //
941 // float2 x = (2, 3);
942 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
943 // | 2 4 6 |
944 //
945 // float4 x = (1, 2, 3, 4);
946 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
947 // | 2 4 |
948 //
949
950 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400951 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400952 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500953 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400954 return true;
955 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400956 position += expr->type().columns();
957 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400958 // An input argument would span multiple rows; a helper function is required.
959 return true;
960 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400961 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400962 // We've advanced to the end of a row. Wrap to the start of the next row.
963 position = 0;
964 }
965 }
966
967 return false;
968}
969
970void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400971 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400972 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400973 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400974 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400975 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400976 const Type& argType = arg.type();
977 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400978 this->writeExpression(arg, parentPrecedence);
979 return;
980 }
981
982 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
983 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500984 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400985 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400986 this->write("float");
987 this->write(to_string(matrix.columns()));
988 this->write("x");
989 this->write(to_string(matrix.rows()));
990 this->write("(");
991 this->writeExpression(arg, parentPrecedence);
992 this->write(")");
993 return;
994 }
995 }
996
997 // Emit and invoke a matrix-constructor helper method if one is necessary.
998 if (this->matrixConstructHelperIsNeeded(c)) {
999 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001000 this->write("(");
1001 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001002 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001003 this->write(separator);
1004 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -04001005 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -04001006 }
John Stiles1fa15b12020-05-28 17:36:54 +00001007 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001008 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001009 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001010
1011 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stiles3dba3ee2020-12-02 23:35:49 -05001012 this->writeBaseType(constructorType);
John Stilesea166702020-12-11 17:30:47 -05001013 this->disallowArrayTypes(constructorType, c.fOffset);
John Stiles1bdafbf2020-05-28 12:17:20 -04001014 this->write("(");
1015 const char* separator = "";
1016 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001017 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001018 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -04001019 this->write(separator);
1020 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -05001021 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -04001022 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001023 // Merge scalars and smaller vectors together.
1024 if (!scalarCount) {
John Stiles3dba3ee2020-12-02 23:35:49 -05001025 this->writeBaseType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001026 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -04001027 this->write("(");
1028 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001029 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001030 }
1031 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001032 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001033 this->write(")");
1034 scalarCount = 0;
1035 }
1036 }
1037 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001038}
1039
1040void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001041 if (fRTHeightName.length()) {
1042 this->write("float4(_fragCoord.x, ");
1043 this->write(fRTHeightName.c_str());
1044 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001045 } else {
1046 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
1047 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001048}
1049
1050void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001051 // When assembling out-param helper functions, we copy variables into local clones with matching
1052 // names. We never want to prepend "_in." or "_globals->" when writing these variables since
1053 // we're actually targeting the clones.
1054 if (fIgnoreVariableReferenceModifiers) {
1055 this->writeName(ref.variable()->name());
1056 return;
1057 }
1058
Ethan Nicholas78686922020-10-08 06:46:27 -04001059 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001060 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -04001061 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001062 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001063 case SK_FRAGCOORD_BUILTIN:
1064 this->writeFragCoord();
1065 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001066 case SK_VERTEXID_BUILTIN:
1067 this->write("sk_VertexID");
1068 break;
1069 case SK_INSTANCEID_BUILTIN:
1070 this->write("sk_InstanceID");
1071 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001072 case SK_CLOCKWISE_BUILTIN:
1073 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001074 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -04001075 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
1076 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001077 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001078 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001079 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001080 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001081 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001082 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001083 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -04001084 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1085 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001086 this->write("_uniforms.");
1087 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -04001088 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -04001089 }
1090 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001091 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001092 }
1093}
1094
1095void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001096 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001097 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001098 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001099 this->write("]");
1100}
1101
1102void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001103 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1104 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
1105 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001106 this->write(".");
1107 }
Timothy Liang7d637782018-06-05 09:58:07 -04001108 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001109 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001110 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001111 break;
1112 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001113 if (field->fName == "sk_PointSize") {
1114 this->write("_out->sk_PointSize");
1115 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001116 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001117 this->write("_globals->");
1118 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1119 this->write("->");
1120 }
Timothy Liang651286f2018-06-07 09:55:33 -04001121 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001122 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001123 }
1124}
1125
1126void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001127 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001128 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001129 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001130 SkASSERT(c >= 0 && c <= 3);
1131 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001132 }
1133}
1134
1135MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
1136 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001137 case Token::Kind::TK_STAR: // fall through
1138 case Token::Kind::TK_SLASH: // fall through
1139 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
1140 case Token::Kind::TK_PLUS: // fall through
1141 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
1142 case Token::Kind::TK_SHL: // fall through
1143 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
1144 case Token::Kind::TK_LT: // fall through
1145 case Token::Kind::TK_GT: // fall through
1146 case Token::Kind::TK_LTEQ: // fall through
1147 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
1148 case Token::Kind::TK_EQEQ: // fall through
1149 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
1150 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
1151 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
1152 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
1153 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
1154 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
1155 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
1156 case Token::Kind::TK_EQ: // fall through
1157 case Token::Kind::TK_PLUSEQ: // fall through
1158 case Token::Kind::TK_MINUSEQ: // fall through
1159 case Token::Kind::TK_STAREQ: // fall through
1160 case Token::Kind::TK_SLASHEQ: // fall through
1161 case Token::Kind::TK_PERCENTEQ: // fall through
1162 case Token::Kind::TK_SHLEQ: // fall through
1163 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001164 case Token::Kind::TK_BITWISEANDEQ: // fall through
1165 case Token::Kind::TK_BITWISEXOREQ: // fall through
1166 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
1167 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -04001168 default: ABORT("unsupported binary operator");
1169 }
1170}
1171
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001172void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1173 const Type& result) {
John Stiles368db7c2020-12-29 11:20:08 -05001174 String key = "TimesEqual" + this->typeName(left) + this->typeName(right);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001175 if (fHelpers.find(key) == fHelpers.end()) {
John Stiles368db7c2020-12-29 11:20:08 -05001176 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001177 " left = left * right;\n"
1178 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001179 "}\n",
1180 this->typeName(result).c_str(), this->typeName(left).c_str(),
1181 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001182 }
1183}
1184
Ethan Nicholascc305772017-10-13 16:17:45 -04001185void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1186 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001187 const Expression& left = *b.left();
1188 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001189 const Type& leftType = left.type();
1190 const Type& rightType = right.type();
1191 Token::Kind op = b.getOperator();
1192 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001193 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001194 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001195 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001196 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001197 this->write("all");
1198 needParens = true;
1199 }
1200 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001201 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001202 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001203 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001204 needParens = true;
1205 }
1206 break;
1207 default:
1208 break;
1209 }
1210 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001211 this->write("(");
1212 }
John Stiles9aeed132020-11-24 17:36:06 -05001213 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001214 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001215 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001216 this->writeExpression(left, precedence);
1217 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
1218 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001219 // This doesn't compile in Metal:
1220 // float4 x = float4(1);
1221 // x.xy *= float2x2(...);
1222 // with the error message "non-const reference cannot bind to vector element",
1223 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1224 // as long as the LHS has no side effects, and hope for the best otherwise.
1225 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001226 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001227 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001228 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001229 SkASSERT(opName.endsWith("="));
1230 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001231 this->write(" ");
1232 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001233 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001234 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001235 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001236 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001237 this->write(")");
1238 }
1239}
1240
1241void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1242 Precedence parentPrecedence) {
1243 if (kTernary_Precedence >= parentPrecedence) {
1244 this->write("(");
1245 }
Ethan Nicholasdd218162020-10-08 05:48:01 -04001246 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001247 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001248 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001249 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001250 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001251 if (kTernary_Precedence >= parentPrecedence) {
1252 this->write(")");
1253 }
1254}
1255
1256void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1257 Precedence parentPrecedence) {
1258 if (kPrefix_Precedence >= parentPrecedence) {
1259 this->write("(");
1260 }
John Stilesd6449e92020-11-30 09:13:23 -05001261 this->write(OperatorName(p.getOperator()));
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001262 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001263 if (kPrefix_Precedence >= parentPrecedence) {
1264 this->write(")");
1265 }
1266}
1267
1268void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1269 Precedence parentPrecedence) {
1270 if (kPostfix_Precedence >= parentPrecedence) {
1271 this->write("(");
1272 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001273 this->writeExpression(*p.operand(), kPostfix_Precedence);
John Stilesd6449e92020-11-30 09:13:23 -05001274 this->write(OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001275 if (kPostfix_Precedence >= parentPrecedence) {
1276 this->write(")");
1277 }
1278}
1279
1280void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001281 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001282}
1283
1284void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001285 const Type& type = i.type();
1286 if (type == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001287 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles12739df2020-12-29 09:47:20 -05001288 } else if (type == *fContext.fUShort_Type) {
1289 this->write(to_string(i.value() & 0xffff) + "u");
1290 } else if (type == *fContext.fUByte_Type) {
1291 this->write(to_string(i.value() & 0xff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001292 } else {
John Stiles12739df2020-12-29 09:47:20 -05001293 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001294 }
1295}
1296
1297void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001298 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001299}
1300
1301void MetalCodeGenerator::writeSetting(const Setting& s) {
1302 ABORT("internal error; setting was not folded to a constant during compilation\n");
1303}
1304
John Stiles06b84ef2020-12-09 12:35:48 -05001305void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1306 const char*& separator) {
1307 Requirements requirements = this->requirements(f);
1308 if (requirements & kInputs_Requirement) {
1309 this->write(separator);
1310 this->write("_in");
1311 separator = ", ";
1312 }
1313 if (requirements & kOutputs_Requirement) {
1314 this->write(separator);
1315 this->write("_out");
1316 separator = ", ";
1317 }
1318 if (requirements & kUniforms_Requirement) {
1319 this->write(separator);
1320 this->write("_uniforms");
1321 separator = ", ";
1322 }
1323 if (requirements & kGlobals_Requirement) {
1324 this->write(separator);
1325 this->write("_globals");
1326 separator = ", ";
1327 }
1328 if (requirements & kFragCoord_Requirement) {
1329 this->write(separator);
1330 this->write("_fragCoord");
1331 separator = ", ";
1332 }
1333}
1334
1335void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1336 const char*& separator) {
1337 Requirements requirements = this->requirements(f);
1338 if (requirements & kInputs_Requirement) {
1339 this->write(separator);
1340 this->write("Inputs _in");
1341 separator = ", ";
1342 }
1343 if (requirements & kOutputs_Requirement) {
1344 this->write(separator);
1345 this->write("thread Outputs* _out");
1346 separator = ", ";
1347 }
1348 if (requirements & kUniforms_Requirement) {
1349 this->write(separator);
1350 this->write("Uniforms _uniforms");
1351 separator = ", ";
1352 }
1353 if (requirements & kGlobals_Requirement) {
1354 this->write(separator);
1355 this->write("thread Globals* _globals");
1356 separator = ", ";
1357 }
1358 if (requirements & kFragCoord_Requirement) {
1359 this->write(separator);
1360 this->write("float4 _fragCoord");
1361 separator = ", ";
1362 }
1363}
1364
John Stiles569249b2020-11-03 12:18:22 -05001365bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001366 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001367 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001368 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001369 switch (fProgram.fKind) {
1370 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001371 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001372 break;
1373 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001374 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001375 break;
1376 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001377 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001378 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001379 }
1380 this->write("(Inputs _in [[stage_in]]");
1381 if (-1 != fUniformBuffer) {
1382 this->write(", constant Uniforms& _uniforms [[buffer(" +
1383 to_string(fUniformBuffer) + ")]]");
1384 }
Brian Osman133724c2020-10-28 14:14:39 -04001385 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001386 if (e->is<GlobalVarDeclaration>()) {
1387 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001388 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1389 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1390 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001391 fErrors.error(decls.fOffset,
1392 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001393 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001394 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001395 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001396 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001397 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001398 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001399 }
1400 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001401 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001402 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001403 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001404 this->write(")]]");
1405 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001406 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001407 this->write(SAMPLER_SUFFIX);
1408 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001409 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001410 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001411 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001412 } else if (e->is<InterfaceBlock>()) {
1413 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001414 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001415 continue;
1416 }
John Stilesbc3c41b2020-12-04 10:52:40 -05001417 if (intf.variable().modifiers().fLayout.fBinding < 0) {
1418 fErrors.error(intf.fOffset,
1419 "Metal interface blocks must have 'layout(binding=...)'");
1420 return false;
1421 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001422 this->write(", constant ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001423 this->writeBaseType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001424 this->write("& " );
1425 this->write(fInterfaceBlockNameMap[&intf]);
1426 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001427 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001428 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001429 }
1430 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001431 if (fProgram.fKind == Program::kFragment_Kind) {
1432 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001433 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001434 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001435 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001436 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001437 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001438 } else if (fProgram.fKind == Program::kVertex_Kind) {
1439 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001440 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001441 separator = ", ";
1442 } else {
John Stiles3dba3ee2020-12-02 23:35:49 -05001443 this->writeBaseType(f.returnType());
John Stilesea166702020-12-11 17:30:47 -05001444 this->disallowArrayTypes(f.returnType(), f.fOffset);
Timothy Liang651286f2018-06-07 09:55:33 -04001445 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001446 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001447 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001448 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001449 }
John Stiles569249b2020-11-03 12:18:22 -05001450 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001451 this->write(separator);
1452 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001453 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001454 const Type* type = &param->type();
John Stiles3dba3ee2020-12-02 23:35:49 -05001455 this->writeBaseType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001456 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001457 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001458 }
Timothy Liang651286f2018-06-07 09:55:33 -04001459 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001460 this->writeName(param->name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001461 this->writeArrayDimensions(*type);
Ethan Nicholascc305772017-10-13 16:17:45 -04001462 }
John Stiles569249b2020-11-03 12:18:22 -05001463 this->write(")");
1464 return true;
1465}
Ethan Nicholascc305772017-10-13 16:17:45 -04001466
John Stiles569249b2020-11-03 12:18:22 -05001467void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1468 this->writeFunctionDeclaration(f.declaration());
1469 this->writeLine(";");
1470}
1471
John Stiles986c7fb2020-12-01 14:44:56 -05001472static bool is_block_ending_with_return(const Statement* stmt) {
1473 // This function detects (potentially nested) blocks that end in a return statement.
1474 if (!stmt->is<Block>()) {
1475 return false;
1476 }
1477 const StatementArray& block = stmt->as<Block>().children();
1478 for (int index = block.count(); index--; ) {
1479 const Statement& stmt = *block[index];
1480 if (stmt.is<ReturnStatement>()) {
1481 return true;
1482 }
1483 if (stmt.is<Block>()) {
1484 return is_block_ending_with_return(&stmt);
1485 }
1486 if (!stmt.is<Nop>()) {
1487 break;
1488 }
1489 }
1490 return false;
1491}
1492
John Stiles569249b2020-11-03 12:18:22 -05001493void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001494 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001495
John Stiles569249b2020-11-03 12:18:22 -05001496 if (!this->writeFunctionDeclaration(f.declaration())) {
1497 return;
1498 }
1499
John Stiles986c7fb2020-12-01 14:44:56 -05001500 fCurrentFunction = &f.declaration();
1501 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1502
John Stiles569249b2020-11-03 12:18:22 -05001503 this->writeLine(" {");
1504
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001505 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001506 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001507 this->writeLine(" Outputs _outputStruct;");
1508 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001509 }
John Stilesc67b3622020-05-28 17:53:13 -04001510
Ethan Nicholascc305772017-10-13 16:17:45 -04001511 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001512 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001513 {
1514 AutoOutputStream outputToBuffer(this, &buffer);
1515 fIndentation++;
1516 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1517 if (!stmt->isEmpty()) {
1518 this->writeStatement(*stmt);
1519 this->writeLine();
1520 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001521 }
John Stiles44532372020-12-07 12:33:55 -05001522 if (f.declaration().name() == "main") {
1523 // If the main function doesn't end with a return, we need to synthesize one here.
1524 if (!is_block_ending_with_return(f.body().get())) {
1525 this->writeReturnStatementFromMain();
1526 this->writeLine("");
1527 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001528 }
John Stiles44532372020-12-07 12:33:55 -05001529 fIndentation--;
1530 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001531 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001532 this->write(fFunctionHeader);
1533 this->write(buffer.str());
1534}
1535
1536void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001537 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001538 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1539 this->write("thread ");
1540 }
1541 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001542 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001543 }
1544}
1545
1546void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001547 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001548 return;
1549 }
John Stiles06b84ef2020-12-09 12:35:48 -05001550 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001551 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001552 this->writeLine(intf.typeName() + " {");
1553 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001554 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001555 structType = &structType->componentType();
1556 }
John Stiles3dba3ee2020-12-02 23:35:49 -05001557 fWrittenStructs.push_back(structType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001558 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001559 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001560 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001561 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001562 }
1563 fIndentation--;
1564 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001565 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001566 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001567 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001568 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001569 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001570 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001571 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001572 } else if (intf.arraySize() == Type::kUnsizedArray){
1573 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001574 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001575 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001576 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001577 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001578 }
1579 this->writeLine(";");
1580}
1581
Timothy Liangdc89f192018-06-13 09:20:31 -04001582void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1583 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001584 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001585 int currentOffset = 0;
1586 for (const auto& field: fields) {
1587 int fieldOffset = field.fModifiers.fLayout.fOffset;
1588 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001589 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001590 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1591 return;
1592 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001593 if (fieldOffset != -1) {
1594 if (currentOffset > fieldOffset) {
1595 fErrors.error(parentOffset,
1596 "offset of field '" + field.fName + "' must be at least " +
1597 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001598 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001599 } else if (currentOffset < fieldOffset) {
1600 this->write("char pad");
1601 this->write(to_string(fPaddingCount++));
1602 this->write("[");
1603 this->write(to_string(fieldOffset - currentOffset));
1604 this->writeLine("];");
1605 currentOffset = fieldOffset;
1606 }
1607 int alignment = memoryLayout.alignment(*fieldType);
1608 if (fieldOffset % alignment) {
1609 fErrors.error(parentOffset,
1610 "offset of field '" + field.fName + "' must be a multiple of " +
1611 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001612 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001613 }
1614 }
Brian Osman8609a242020-09-08 14:01:49 -04001615 size_t fieldSize = memoryLayout.size(*fieldType);
1616 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1617 fErrors.error(parentOffset, "field offset overflow");
1618 return;
1619 }
1620 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001621 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stiles3dba3ee2020-12-02 23:35:49 -05001622 this->writeBaseType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001623 this->write(" ");
1624 this->writeName(field.fName);
John Stiles3dba3ee2020-12-02 23:35:49 -05001625 this->writeArrayDimensions(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001626 this->writeLine(";");
1627 if (parentIntf) {
1628 fInterfaceBlockMap[&field] = parentIntf;
1629 }
1630 }
1631}
1632
Ethan Nicholascc305772017-10-13 16:17:45 -04001633void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1634 this->writeExpression(value, kTopLevel_Precedence);
1635}
1636
Timothy Liang651286f2018-06-07 09:55:33 -04001637void MetalCodeGenerator::writeName(const String& name) {
1638 if (fReservedWords.find(name) != fReservedWords.end()) {
1639 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1640 }
1641 this->write(name);
1642}
1643
Brian Osmanc0213602020-10-06 14:43:32 -04001644void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001645 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001646 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001647 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001648 this->writeModifiers(var.var().modifiers(), global);
John Stiles3dba3ee2020-12-02 23:35:49 -05001649 this->writeBaseType(var.baseType());
John Stilesea166702020-12-11 17:30:47 -05001650 this->disallowArrayTypes(var.baseType(), var.fOffset);
Brian Osmanc0213602020-10-06 14:43:32 -04001651 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001652 this->writeName(var.var().name());
John Stiles62a56462020-12-03 10:41:58 -05001653 if (var.arraySize() > 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001654 this->write("[");
John Stiles62a56462020-12-03 10:41:58 -05001655 this->write(to_string(var.arraySize()));
Brian Osmanc0213602020-10-06 14:43:32 -04001656 this->write("]");
John Stiles62a56462020-12-03 10:41:58 -05001657 } else if (var.arraySize() == Type::kUnsizedArray){
1658 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001659 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001660 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001661 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001662 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001663 }
1664 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001665}
1666
1667void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001668 switch (s.kind()) {
1669 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001670 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001671 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001672 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001673 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001674 this->write(";");
1675 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001676 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001677 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001678 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001679 case Statement::Kind::kVarDeclaration:
1680 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001681 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001682 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001683 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001684 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001685 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001686 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001687 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001688 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001689 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001690 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001691 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001692 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001693 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001694 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001695 this->write("break;");
1696 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001697 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001698 this->write("continue;");
1699 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001700 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001701 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001702 break;
John Stiles98c1f822020-09-09 14:18:53 -04001703 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001704 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001705 this->write(";");
1706 break;
1707 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001708#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001709 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001710#endif
1711 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001712 }
1713}
1714
Ethan Nicholascc305772017-10-13 16:17:45 -04001715void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001716 bool isScope = b.isScope();
1717 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001718 this->writeLine("{");
1719 fIndentation++;
1720 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001721 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1722 if (!stmt->isEmpty()) {
1723 this->writeStatement(*stmt);
1724 this->writeLine();
1725 }
1726 }
1727 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001728 fIndentation--;
1729 this->write("}");
1730 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001731}
1732
1733void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1734 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001735 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001736 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001737 this->writeStatement(*stmt.ifTrue());
1738 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001739 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001740 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001741 }
1742}
1743
1744void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05001745 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
1746 if (!f.initializer() && f.test() && !f.next()) {
1747 this->write("while (");
1748 this->writeExpression(*f.test(), kTopLevel_Precedence);
1749 this->write(") ");
1750 this->writeStatement(*f.statement());
1751 return;
1752 }
1753
Ethan Nicholascc305772017-10-13 16:17:45 -04001754 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001755 if (f.initializer() && !f.initializer()->isEmpty()) {
1756 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001757 } else {
1758 this->write("; ");
1759 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001760 if (f.test()) {
1761 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001762 }
1763 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001764 if (f.next()) {
1765 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001766 }
1767 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001768 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001769}
1770
Ethan Nicholascc305772017-10-13 16:17:45 -04001771void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1772 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001773 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001774 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001775 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001776 this->write(");");
1777}
1778
1779void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1780 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001781 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001782 this->writeLine(") {");
1783 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001784 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1785 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001786 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001787 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001788 this->writeLine(":");
1789 } else {
1790 this->writeLine("default:");
1791 }
1792 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001793 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001794 this->writeStatement(*stmt);
1795 this->writeLine();
1796 }
1797 fIndentation--;
1798 }
1799 fIndentation--;
1800 this->write("}");
1801}
1802
John Stiles986c7fb2020-12-01 14:44:56 -05001803void MetalCodeGenerator::writeReturnStatementFromMain() {
1804 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
1805 switch (fProgram.fKind) {
1806 case Program::kFragment_Kind:
1807 this->write("return *_out;");
1808 break;
1809 case Program::kVertex_Kind:
1810 this->write("return (_out->sk_Position.y = -_out->sk_Position.y, *_out);");
1811 break;
1812 default:
1813 SkDEBUGFAIL("unsupported kind of program");
1814 }
1815}
1816
Ethan Nicholascc305772017-10-13 16:17:45 -04001817void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stiles986c7fb2020-12-01 14:44:56 -05001818 if (fCurrentFunction && fCurrentFunction->name() == "main") {
1819 if (r.expression()) {
1820 fErrors.error(r.fOffset, "Metal does not support returning values from main()");
1821 }
1822 this->writeReturnStatementFromMain();
1823 return;
1824 }
1825
Ethan Nicholascc305772017-10-13 16:17:45 -04001826 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001827 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001828 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001829 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001830 }
1831 this->write(";");
1832}
1833
1834void MetalCodeGenerator::writeHeader() {
1835 this->write("#include <metal_stdlib>\n");
1836 this->write("#include <simd/simd.h>\n");
1837 this->write("using namespace metal;\n");
1838}
1839
1840void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001841 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001842 if (e->is<GlobalVarDeclaration>()) {
1843 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001844 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001845 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001846 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001847 if (-1 == fUniformBuffer) {
1848 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001849 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001850 if (-1 == fUniformBuffer) {
1851 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1852 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001853 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001854 if (-1 == fUniformBuffer) {
1855 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1856 "the same 'layout(set=...)'");
1857 }
1858 }
1859 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001860 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001861 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001862 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001863 this->writeArrayDimensions(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001864 this->write(";\n");
1865 }
1866 }
1867 }
1868 if (-1 != fUniformBuffer) {
1869 this->write("};\n");
1870 }
1871}
1872
1873void MetalCodeGenerator::writeInputStruct() {
1874 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001875 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001876 if (e->is<GlobalVarDeclaration>()) {
1877 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001878 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001879 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1880 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001881 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001882 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001883 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001884 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001885 this->writeArrayDimensions(var.type());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001886 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001887 if (fProgram.fKind == Program::kVertex_Kind) {
1888 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001889 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001890 } else if (fProgram.fKind == Program::kFragment_Kind) {
1891 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001892 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001893 }
1894 }
1895 this->write(";\n");
1896 }
1897 }
1898 }
1899 this->write("};\n");
1900}
1901
1902void MetalCodeGenerator::writeOutputStruct() {
1903 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001904 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001905 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001906 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001907 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001908 }
Brian Osman133724c2020-10-28 14:14:39 -04001909 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001910 if (e->is<GlobalVarDeclaration>()) {
1911 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001912 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001913 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1914 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001915 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001916 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001917 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001918 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001919 this->writeArrayDimensions(var.type());
John Stiles842b3592020-12-01 10:36:37 -05001920
1921 int location = var.modifiers().fLayout.fLocation;
1922 if (location < 0) {
1923 fErrors.error(var.fOffset,
1924 "Metal out variables must have 'layout(location=...)'");
1925 } else if (fProgram.fKind == Program::kVertex_Kind) {
1926 this->write(" [[user(locn" + to_string(location) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001927 } else if (fProgram.fKind == Program::kFragment_Kind) {
John Stiles842b3592020-12-01 10:36:37 -05001928 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001929 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001930 if (colorIndex) {
1931 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001932 }
Brian Osmanc0213602020-10-06 14:43:32 -04001933 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001934 }
1935 this->write(";\n");
1936 }
1937 }
Timothy Liang7d637782018-06-05 09:58:07 -04001938 }
1939 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001940 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001941 }
1942 this->write("};\n");
1943}
1944
1945void MetalCodeGenerator::writeInterfaceBlocks() {
1946 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001947 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001948 if (e->is<InterfaceBlock>()) {
1949 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001950 wroteInterfaceBlock = true;
1951 }
1952 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001953 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001954 this->writeLine("struct sksl_synthetic_uniforms {");
1955 this->writeLine(" float u_skRTHeight;");
1956 this->writeLine("};");
1957 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001958}
1959
John Stilesdc75a972020-11-25 16:24:55 -05001960void MetalCodeGenerator::writeStructDefinitions() {
1961 for (const ProgramElement* e : fProgram.elements()) {
1962 if (e->is<StructDefinition>()) {
1963 if (this->writeStructDefinition(e->as<StructDefinition>().type())) {
1964 this->writeLine(";");
1965 }
1966 } else if (e->is<GlobalVarDeclaration>()) {
1967 // If a global var declaration introduces a struct type, we need to write that type
1968 // here, since globals are all embedded in a sub-struct.
1969 const Type* type = &e->as<GlobalVarDeclaration>().declaration()
1970 ->as<VarDeclaration>().baseType();
John Stilesc0c51062020-12-03 17:16:29 -05001971 if (type->isStruct()) {
John Stilesdc75a972020-11-25 16:24:55 -05001972 if (this->writeStructDefinition(*type)) {
1973 this->writeLine(";");
1974 }
1975 }
1976 }
1977 }
1978}
1979
John Stilescdcdb042020-07-06 09:03:51 -04001980void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1981 // Visit the interface blocks.
1982 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05001983 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04001984 }
Brian Osman133724c2020-10-28 14:14:39 -04001985 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001986 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001987 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001988 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001989 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1990 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1991 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001992 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001993 var.type().typeKind() == Type::TypeKind::kSampler) {
1994 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1995 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001996 visitor->visitTexture(var.type(), var.name());
1997 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04001998 } else {
1999 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05002000 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002001 }
2002 }
2003 }
John Stilescdcdb042020-07-06 09:03:51 -04002004}
2005
2006void MetalCodeGenerator::writeGlobalStruct() {
2007 class : public GlobalStructVisitor {
2008 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002009 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002010 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002011 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002012 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002013 fCodeGen->write("* ");
2014 fCodeGen->writeName(blockName);
2015 fCodeGen->write(";\n");
2016 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002017 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002018 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002019 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05002020 fCodeGen->writeBaseType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002021 fCodeGen->write(" ");
2022 fCodeGen->writeName(name);
John Stiles3dba3ee2020-12-02 23:35:49 -05002023 fCodeGen->writeArrayDimensions(type);
John Stilescdcdb042020-07-06 09:03:51 -04002024 fCodeGen->write(";\n");
2025 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002026 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002027 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002028 fCodeGen->write(" sampler ");
2029 fCodeGen->writeName(name);
2030 fCodeGen->write(";\n");
2031 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002032 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002033 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002034 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05002035 fCodeGen->writeBaseType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002036 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002037 fCodeGen->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05002038 fCodeGen->writeArrayDimensions(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002039 fCodeGen->write(";\n");
2040 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002041 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002042 if (fFirst) {
2043 fCodeGen->write("struct Globals {\n");
2044 fFirst = false;
2045 }
2046 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002047 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002048 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002049 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002050 fFirst = true;
2051 }
2052 }
2053
2054 MetalCodeGenerator* fCodeGen = nullptr;
2055 bool fFirst = true;
2056 } visitor;
2057
2058 visitor.fCodeGen = this;
2059 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002060 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002061}
2062
2063void MetalCodeGenerator::writeGlobalInit() {
2064 class : public GlobalStructVisitor {
2065 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002066 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04002067 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002068 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002069 fCodeGen->write("&");
2070 fCodeGen->writeName(blockName);
2071 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002072 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002073 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002074 fCodeGen->writeName(name);
2075 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002076 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002077 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002078 fCodeGen->writeName(name);
2079 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002080 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002081 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002082 if (value) {
2083 fCodeGen->writeVarInitializer(var, *value);
2084 } else {
2085 fCodeGen->write("{}");
2086 }
2087 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002088 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002089 if (fFirst) {
2090 fCodeGen->write(" Globals globalStruct{");
2091 fFirst = false;
2092 } else {
2093 fCodeGen->write(", ");
2094 }
2095 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002096 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002097 if (!fFirst) {
2098 fCodeGen->writeLine("};");
2099 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
2100 fCodeGen->writeLine(" (void)_globals;");
2101 }
2102 }
2103 MetalCodeGenerator* fCodeGen = nullptr;
2104 bool fFirst = true;
2105 } visitor;
2106
2107 visitor.fCodeGen = this;
2108 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002109 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002110}
2111
Ethan Nicholascc305772017-10-13 16:17:45 -04002112void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002113 switch (e.kind()) {
2114 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002115 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002116 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002117 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2118 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2119 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002120 if (-1 == builtin) {
2121 // normal var
2122 this->writeVarDeclaration(decl, true);
2123 this->writeLine();
2124 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2125 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002126 }
2127 break;
2128 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002129 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002130 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002131 break;
John Stilesdc75a972020-11-25 16:24:55 -05002132 case ProgramElement::Kind::kStructDefinition:
2133 // Handled in writeStructDefinitions. Do nothing.
2134 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002135 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002136 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002137 break;
John Stiles569249b2020-11-03 12:18:22 -05002138 case ProgramElement::Kind::kFunctionPrototype:
2139 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2140 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002141 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002142 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2143 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002144 this->writeLine(";");
2145 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002146 case ProgramElement::Kind::kEnum:
2147 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002148 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002149#ifdef SK_DEBUG
2150 ABORT("unsupported program element: %s\n", e.description().c_str());
2151#endif
2152 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002153 }
2154}
2155
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002156MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2157 if (!e) {
2158 return kNo_Requirements;
2159 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002160 switch (e->kind()) {
2161 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002162 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002163 Requirements result = this->requirements(f.function());
2164 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002165 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002166 }
2167 return result;
2168 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002169 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002170 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04002171 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002172 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002173 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002174 }
2175 return result;
2176 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002177 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002178 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002179 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002180 return kGlobals_Requirement;
2181 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002182 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002183 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002184 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002185 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002186 case Expression::Kind::kBinary: {
2187 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002188 return this->requirements(bin.left().get()) |
2189 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002190 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002191 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002192 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002193 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002194 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002195 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002196 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002197 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002198 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002199 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002200 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002201 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2202 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002203 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002204 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002205 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002206 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002207 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002208 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002209 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002210 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002211 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002212 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002213 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002214 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002215 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002216 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002217 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002218 } else {
2219 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002220 }
2221 }
2222 return result;
2223 }
2224 default:
2225 return kNo_Requirements;
2226 }
2227}
2228
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002229MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2230 if (!s) {
2231 return kNo_Requirements;
2232 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002233 switch (s->kind()) {
2234 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002235 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002236 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002237 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002238 }
2239 return result;
2240 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002241 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002242 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002243 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002244 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002245 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002246 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002247 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002248 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002249 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002250 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002251 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002252 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002253 return this->requirements(i.test().get()) |
2254 this->requirements(i.ifTrue().get()) |
2255 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002256 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002257 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002258 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002259 return this->requirements(f.initializer().get()) |
2260 this->requirements(f.test().get()) |
2261 this->requirements(f.next().get()) |
2262 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002263 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002264 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002265 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002266 return this->requirements(d.test().get()) |
2267 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002268 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002269 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002270 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002271 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04002272 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
2273 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002274 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002275 }
2276 }
2277 return result;
2278 }
2279 default:
2280 return kNo_Requirements;
2281 }
2282}
2283
2284MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002285 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002286 return kNo_Requirements;
2287 }
2288 auto found = fRequirements.find(&f);
2289 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002290 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002291 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002292 if (e->is<FunctionDefinition>()) {
2293 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002294 if (&def.declaration() == &f) {
2295 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002296 fRequirements[&f] = reqs;
2297 return reqs;
2298 }
2299 }
2300 }
John Stiles569249b2020-11-03 12:18:22 -05002301 // We never found a definition for this declared function, but it's legal to prototype a
2302 // function without ever giving a definition, as long as you don't call it.
2303 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002304 }
2305 return found->second;
2306}
2307
Timothy Liangb8eeb802018-07-23 16:46:16 -04002308bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04002309 fProgramKind = fProgram.fKind;
Ethan Nicholascc305772017-10-13 16:17:45 -04002310
John Stiles44532372020-12-07 12:33:55 -05002311 StringStream header;
2312 {
2313 AutoOutputStream outputToHeader(this, &header, &fIndentation);
2314 this->writeHeader();
2315 this->writeStructDefinitions();
2316 this->writeUniformStruct();
2317 this->writeInputStruct();
2318 this->writeOutputStruct();
2319 this->writeInterfaceBlocks();
2320 this->writeGlobalStruct();
2321 }
2322 StringStream body;
2323 {
2324 AutoOutputStream outputToBody(this, &body, &fIndentation);
2325 for (const ProgramElement* e : fProgram.elements()) {
2326 this->writeProgramElement(*e);
2327 }
2328 }
2329 write_stringstream(header, *fOut);
2330 write_stringstream(fExtraFunctions, *fOut);
2331 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002332 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002333}
2334
John Stilesa6841be2020-08-06 14:11:56 -04002335} // namespace SkSL