blob: d3f8ea1384e3d847d681866d37be147ca3c05574 [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);
Brian Osman46787d52020-11-24 14:18:23 -050052 fIntrinsicMap[String("length")] = SPECIAL(Length);
Timothy Liang651286f2018-06-07 09:55:33 -040053 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Brian Osman46787d52020-11-24 14:18:23 -050054 fIntrinsicMap[String("normalize")] = SPECIAL(Normalize);
John Stilese2d34f82020-12-10 18:02:02 -050055 fIntrinsicMap[String("radians")] = SPECIAL(Radians);
Brian Osman46787d52020-11-24 14:18:23 -050056 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050057 fIntrinsicMap[String("equal")] = METAL(Equal);
58 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040059 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
60 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
61 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
62 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Timothy Liangee84fe12018-05-18 14:38:19 -040063}
64
Ethan Nicholascc305772017-10-13 16:17:45 -040065void MetalCodeGenerator::write(const char* s) {
66 if (!s[0]) {
67 return;
68 }
69 if (fAtLineStart) {
70 for (int i = 0; i < fIndentation; i++) {
71 fOut->writeText(" ");
72 }
73 }
74 fOut->writeText(s);
75 fAtLineStart = false;
76}
77
78void MetalCodeGenerator::writeLine(const char* s) {
79 this->write(s);
80 fOut->writeText(fLineEnding);
81 fAtLineStart = true;
82}
83
84void MetalCodeGenerator::write(const String& s) {
85 this->write(s.c_str());
86}
87
88void MetalCodeGenerator::writeLine(const String& s) {
89 this->writeLine(s.c_str());
90}
91
92void MetalCodeGenerator::writeLine() {
93 this->writeLine("");
94}
95
96void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040097 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040098}
99
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500100String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400101 switch (type.typeKind()) {
102 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500103 return this->typeName(type.componentType()) + to_string(type.columns());
Ethan Nicholase6592142020-09-08 10:22:09 -0400104 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500105 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
106 to_string(type.rows());
Ethan Nicholase6592142020-09-08 10:22:09 -0400107 case Type::TypeKind::kSampler:
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500108 return "texture2d<float>"; // FIXME - support other texture types;
John Stilesfd41d872020-11-25 22:39:45 -0500109 case Type::TypeKind::kEnum:
110 return "int";
Ethan Nicholascc305772017-10-13 16:17:45 -0400111 default:
Timothy Liang43d225f2018-07-19 15:27:13 -0400112 if (type == *fContext.fHalf_Type) {
113 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500114 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -0400115 } else if (type == *fContext.fByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500116 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -0400117 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500118 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -0400119 } else {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500120 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -0400121 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400122 }
123}
124
John Stilesdc75a972020-11-25 16:24:55 -0500125bool MetalCodeGenerator::writeStructDefinition(const Type& type) {
126 for (const Type* search : fWrittenStructs) {
127 if (*search == type) {
128 // already written
129 return false;
130 }
131 }
132 fWrittenStructs.push_back(&type);
133 this->writeLine("struct " + type.name() + " {");
134 fIndentation++;
135 this->writeFields(type.fields(), type.fOffset);
136 fIndentation--;
137 this->write("}");
138 return true;
139}
140
John Stiles3dba3ee2020-12-02 23:35:49 -0500141// Flags an error if an array type is found. Meant to be used in places where an array type might
142// appear in the SkSL/IR, but can't be represented by Metal.
143void MetalCodeGenerator::disallowArrayTypes(const Type& type) {
John Stilesc0c51062020-12-03 17:16:29 -0500144 if (type.isArray()) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500145 fErrors.error(type.fOffset, "Metal does not support array types in this context");
146 }
147}
148
149// Writes the base type, stripping array suffixes. e.g. `float[2]` will output `float`.
150// Call `writeArrayDimensions` to write the type's accompanying array sizes.
151void MetalCodeGenerator::writeBaseType(const Type& type) {
152 switch (type.typeKind()) {
153 case Type::TypeKind::kStruct:
154 if (!this->writeStructDefinition(type)) {
155 this->write(type.name());
156 }
157 break;
158 case Type::TypeKind::kArray:
159 this->writeBaseType(type.componentType());
160 break;
161 default:
162 this->write(this->typeName(type));
163 break;
164 }
165}
166
167// Writes the array suffix of a type, if one exists. e.g. `float[2][4]` will output `[2][4]`.
168void MetalCodeGenerator::writeArrayDimensions(const Type& type) {
John Stilesc0c51062020-12-03 17:16:29 -0500169 if (type.isArray()) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500170 this->write("[");
171 if (type.columns() != Type::kUnsizedArray) {
172 this->write(to_string(type.columns()));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500173 }
John Stiles3dba3ee2020-12-02 23:35:49 -0500174 this->write("]");
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500175 }
176}
177
Ethan Nicholascc305772017-10-13 16:17:45 -0400178void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400179 switch (expr.kind()) {
180 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400181 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400182 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400183 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400184 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400185 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400186 case Expression::Kind::kConstructor:
John Stiles81365af2020-08-18 09:24:00 -0400187 this->writeConstructor(expr.as<Constructor>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400188 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400189 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400190 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400191 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400192 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400193 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400194 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400195 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400196 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400197 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400198 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400199 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400200 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400201 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400202 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400203 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400204 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400205 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400206 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400207 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400208 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400209 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400210 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400211 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400212 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400213 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400214 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400215 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400216 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400217 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400218 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400219 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400220 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400221 break;
222 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500223#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -0400224 ABORT("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500225#endif
226 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400227 }
228}
229
Timothy Liang6403b0e2018-05-17 10:40:04 -0400230void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400231 auto i = fIntrinsicMap.find(c.function().name());
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400232 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400233 Intrinsic intrinsic = i->second;
234 int32_t intrinsicId = intrinsic.second;
235 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400236 case kSpecial_IntrinsicKind:
237 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400238 break;
239 case kMetal_IntrinsicKind:
John Stiles47b4b192020-12-08 18:08:11 -0500240 this->write("(");
241 this->writeExpression(*c.arguments()[0], kRelational_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400242 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500243 case kEqual_MetalIntrinsic:
244 this->write(" == ");
245 break;
246 case kNotEqual_MetalIntrinsic:
247 this->write(" != ");
248 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400249 case kLessThan_MetalIntrinsic:
250 this->write(" < ");
251 break;
252 case kLessThanEqual_MetalIntrinsic:
253 this->write(" <= ");
254 break;
255 case kGreaterThan_MetalIntrinsic:
256 this->write(" > ");
257 break;
258 case kGreaterThanEqual_MetalIntrinsic:
259 this->write(" >= ");
260 break;
261 default:
John Stiles47b4b192020-12-08 18:08:11 -0500262 ABORT("unsupported Metal intrinsic kind");
Timothy Lianga06f2152018-05-24 15:33:31 -0400263 }
John Stiles47b4b192020-12-08 18:08:11 -0500264 this->writeExpression(*c.arguments()[1], kRelational_Precedence);
265 this->write(")");
Timothy Lianga06f2152018-05-24 15:33:31 -0400266 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400267 default:
268 ABORT("unsupported intrinsic kind");
269 }
270}
271
John Stiles06b84ef2020-12-09 12:35:48 -0500272String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
273 const ExpressionArray& arguments,
274 const SkTArray<VariableReference*>& outVars) {
275 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
276 const FunctionDeclaration& function = call.function();
277
278 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) + "_" + function.name();
279 const char* separator = "";
280
281 // Emit a prototype for the function we'll be calling through to in our helper.
282 if (!function.isBuiltin()) {
283 this->writeFunctionDeclaration(function);
284 this->writeLine(";");
285 }
286
287 // Synthesize a helper function that takes the same inputs as `function`, except in places where
288 // `outVars` is non-null; in those places, we take the type of the VariableReference.
289 //
290 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
291 this->writeBaseType(call.type());
292 this->write(" ");
293 this->write(name);
294 this->write("(");
295 this->writeFunctionRequirementParams(function, separator);
296
297 SkASSERT(outVars.size() == arguments.size());
298 SkASSERT(outVars.size() == function.parameters().size());
299
300 for (int index = 0; index < arguments.count(); ++index) {
301 this->write(separator);
302 separator = ", ";
303
304 const Variable* param = function.parameters()[index];
305 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
306
307 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
308 this->writeBaseType(*type);
309
310 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
311 this->write("&");
312 }
313 if (outVars[index]) {
314 this->write(" ");
315 fIgnoreVariableReferenceModifiers = true;
316 this->writeVariableReference(*outVars[index]);
317 fIgnoreVariableReferenceModifiers = false;
318 } else {
319 this->write(" _var");
320 this->write(to_string(index));
321 }
322 this->writeArrayDimensions(*type);
323 }
324 this->writeLine(") {");
325
326 ++fIndentation;
327 for (int index = 0; index < outVars.count(); ++index) {
328 if (!outVars[index]) {
329 continue;
330 }
331 // float3 _var2[ = outParam.zyx];
332 this->writeBaseType(arguments[index]->type());
333 this->write(" _var");
334 this->write(to_string(index));
335
336 const Variable* param = function.parameters()[index];
337 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
338 this->write(" = ");
339 fIgnoreVariableReferenceModifiers = true;
340 this->writeExpression(*arguments[index], kAssignment_Precedence);
341 fIgnoreVariableReferenceModifiers = false;
342 }
343
344 this->writeLine(";");
345 }
346
347 // [int _skResult = ] myFunction(inputs, outputs, globals, _var0, _var1, _var2, _var3);
348 bool hasResult = (call.type().name() != "void");
349 if (hasResult) {
350 this->writeBaseType(call.type());
351 this->write(" _skResult = ");
352 }
353
354 this->writeName(function.name());
355 this->write("(");
356 separator = "";
357 this->writeFunctionRequirementArgs(function, separator);
358
359 for (int index = 0; index < arguments.count(); ++index) {
360 this->write(separator);
361 separator = ", ";
362
363 this->write("_var");
364 this->write(to_string(index));
365 }
366 this->writeLine(");");
367
368 for (int index = 0; index < outVars.count(); ++index) {
369 if (!outVars[index]) {
370 continue;
371 }
372 // outParam.zyx = _var2;
373 fIgnoreVariableReferenceModifiers = true;
374 this->writeExpression(*arguments[index], kAssignment_Precedence);
375 fIgnoreVariableReferenceModifiers = false;
376 this->write(" = _var");
377 this->write(to_string(index));
378 this->writeLine(";");
379 }
380
381 if (hasResult) {
382 this->writeLine("return _skResult;");
383 }
384
385 --fIndentation;
386 this->writeLine("}");
387
388 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500389}
390
John Stilesf64e4072020-12-10 10:34:27 -0500391String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
392 return "as_type<" + outType.displayName() + ">";
393}
394
Ethan Nicholascc305772017-10-13 16:17:45 -0400395void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400396 const FunctionDeclaration& function = c.function();
John Stiles8e3b6be2020-10-13 11:14:08 -0400397 const ExpressionArray& arguments = c.arguments();
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400398 const auto& entry = fIntrinsicMap.find(function.name());
Timothy Liang6403b0e2018-05-17 10:40:04 -0400399 if (entry != fIntrinsicMap.end()) {
400 this->writeIntrinsicCall(c);
401 return;
402 }
John Stilesb21fac22020-12-04 15:36:49 -0500403 String name = function.name();
John Stilesb21fac22020-12-04 15:36:49 -0500404
John Stilesf64e4072020-12-10 10:34:27 -0500405 if (function.isBuiltin()) {
406 if (name == "atan" && arguments.size() == 2) {
407 name = "atan2";
408 } else if (name == "inversesqrt") {
409 name = "rsqrt";
410 } else if (name == "inverse") {
411 SkASSERT(arguments.size() == 1);
412 name = this->getInverseHack(*arguments[0]);
413 } else if (name == "dFdx") {
414 name = "dfdx";
415 } else if (name == "dFdy") {
416 // Flipping Y also negates the Y derivatives.
417 if (fProgram.fSettings.fFlipY) {
418 this->write("-");
419 }
420 name = "dfdy";
John Stilesb21fac22020-12-04 15:36:49 -0500421 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400422 }
John Stilesb21fac22020-12-04 15:36:49 -0500423
John Stilesf64e4072020-12-10 10:34:27 -0500424 // We emulate GLSL's out-param semantics for Metal using a helper function. (Specifically,
425 // results are only written back to the original variable at the end of the function call; also,
426 // swizzles are supported, whereas Metal doesn't allow a swizzle to be passed to a `floatN&`.)
John Stilesb21fac22020-12-04 15:36:49 -0500427 const std::vector<const Variable*>& parameters = function.parameters();
428 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500429
430 bool foundOutParam = false;
431 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500432 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500433
434 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500435 // If this is an out parameter...
436 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500437 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500438 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500439 // Assignability was verified at IRGeneration time, so this should always succeed.
440 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
441 outVars[index] = info.fAssignedVar;
442 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500443 }
444 }
445
John Stiles06b84ef2020-12-09 12:35:48 -0500446 if (foundOutParam) {
447 // Out parameters need to be written back to at the end of the function. To do this, we
448 // synthesize a helper function which evaluates the out-param expression into a temporary
449 // variable, calls the original function, then writes the temp var back into the out param
450 // using the original out-param expression. (This lets us support things like swizzles and
451 // array indices.)
452 name = getOutParamHelper(c, arguments, outVars);
453 }
454
John Stilesb21fac22020-12-04 15:36:49 -0500455 this->write(name);
Ethan Nicholascc305772017-10-13 16:17:45 -0400456 this->write("(");
457 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500458 this->writeFunctionRequirementArgs(function, separator);
459 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400460 this->write(separator);
461 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500462
463 if (outVars[i]) {
464 this->writeExpression(*outVars[i], kSequence_Precedence);
465 } else {
466 this->writeExpression(*arguments[i], kSequence_Precedence);
467 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400468 }
469 this->write(")");
470}
471
John Stilesb21fac22020-12-04 15:36:49 -0500472String MetalCodeGenerator::getInverseHack(const Expression& mat) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400473 const Type& type = mat.type();
474 const String& typeName = type.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500475 String name = typeName + "_inverse";
Ethan Nicholas30d30222020-09-11 12:27:26 -0400476 if (type == *fContext.fFloat2x2_Type || type == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500477 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
478 fWrittenIntrinsics.insert(name);
479 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500480 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500481 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
482 "}"
483 ).c_str());
484 }
485 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400486 else if (type == *fContext.fFloat3x3_Type || type == *fContext.fHalf3x3_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500487 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
488 fWrittenIntrinsics.insert(name);
489 fExtraFunctions.writeText((
490 typeName + " " + name + "(" + typeName + " m) {"
491 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
492 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
493 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
494 " float b01 = a22 * a11 - a12 * a21;"
495 " float b11 = -a22 * a10 + a12 * a20;"
496 " float b21 = a21 * a10 - a11 * a20;"
497 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
498 " return " + typeName +
499 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
500 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
501 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
502 " (1/det);"
503 "}"
504 ).c_str());
505 }
506 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400507 else if (type == *fContext.fFloat4x4_Type || type == *fContext.fHalf4x4_Type) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500508 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
509 fWrittenIntrinsics.insert(name);
510 fExtraFunctions.writeText((
511 typeName + " " + name + "(" + typeName + " m) {"
512 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
513 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
514 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
515 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
516 " float b00 = a00 * a11 - a01 * a10;"
517 " float b01 = a00 * a12 - a02 * a10;"
518 " float b02 = a00 * a13 - a03 * a10;"
519 " float b03 = a01 * a12 - a02 * a11;"
520 " float b04 = a01 * a13 - a03 * a11;"
521 " float b05 = a02 * a13 - a03 * a12;"
522 " float b06 = a20 * a31 - a21 * a30;"
523 " float b07 = a20 * a32 - a22 * a30;"
524 " float b08 = a20 * a33 - a23 * a30;"
525 " float b09 = a21 * a32 - a22 * a31;"
526 " float b10 = a21 * a33 - a23 * a31;"
527 " float b11 = a22 * a33 - a23 * a32;"
528 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
529 " b04 * b07 + b05 * b06;"
530 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
531 " a02 * b10 - a01 * b11 - a03 * b09,"
532 " a31 * b05 - a32 * b04 + a33 * b03,"
533 " a22 * b04 - a21 * b05 - a23 * b03,"
534 " a12 * b08 - a10 * b11 - a13 * b07,"
535 " a00 * b11 - a02 * b08 + a03 * b07,"
536 " a32 * b02 - a30 * b05 - a33 * b01,"
537 " a20 * b05 - a22 * b02 + a23 * b01,"
538 " a10 * b10 - a11 * b08 + a13 * b06,"
539 " a01 * b08 - a00 * b10 - a03 * b06,"
540 " a30 * b04 - a31 * b02 + a33 * b00,"
541 " a21 * b02 - a20 * b04 - a23 * b00,"
542 " a11 * b07 - a10 * b09 - a12 * b06,"
543 " a00 * b09 - a01 * b07 + a02 * b06,"
544 " a31 * b01 - a30 * b03 - a32 * b00,"
545 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
546 "}"
547 ).c_str());
548 }
549 }
John Stilesb21fac22020-12-04 15:36:49 -0500550 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500551}
552
Timothy Liang6403b0e2018-05-17 10:40:04 -0400553void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400554 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400555 switch (kind) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400556 case kTexture_SpecialIntrinsic: {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400557 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400558 this->write(".sample(");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400559 this->writeExpression(*arguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400560 this->write(SAMPLER_SUFFIX);
561 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400562 const Type& arg1Type = arguments[1]->type();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400563 if (arg1Type == *fContext.fFloat3_Type) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500564 // have to store the vector in a temp variable to avoid double evaluating it
565 String tmpVar = "tmpCoord" + to_string(fVarCount++);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400566 this->fFunctionHeader += " " + this->typeName(arg1Type) + " " + tmpVar + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500567 this->write("(" + tmpVar + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400568 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500569 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400570 } else {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400571 SkASSERT(arg1Type == *fContext.fFloat2_Type);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400572 this->writeExpression(*arguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400573 this->write(")");
574 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400575 break;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400576 }
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500577 case kMod_SpecialIntrinsic: {
Timothy Liang651286f2018-06-07 09:55:33 -0400578 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500579 String tmpX = "tmpX" + to_string(fVarCount++);
580 String tmpY = "tmpY" + to_string(fVarCount++);
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400581 this->fFunctionHeader += " " + this->typeName(arguments[0]->type()) +
Ethan Nicholas30d30222020-09-11 12:27:26 -0400582 " " + tmpX + ", " + tmpY + ";\n";
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500583 this->write("(" + tmpX + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400584 this->writeExpression(*arguments[0], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500585 this->write(", " + tmpY + " = ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400586 this->writeExpression(*arguments[1], kSequence_Precedence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500587 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
Timothy Liang651286f2018-06-07 09:55:33 -0400588 break;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500589 }
Brian Osman46787d52020-11-24 14:18:23 -0500590 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
591 case kDistance_SpecialIntrinsic: {
592 if (arguments[0]->type().columns() == 1) {
593 this->write("abs(");
594 this->writeExpression(*arguments[0], kAdditive_Precedence);
595 this->write(" - ");
596 this->writeExpression(*arguments[1], kAdditive_Precedence);
597 this->write(")");
598 } else {
599 this->write("distance(");
600 this->writeExpression(*arguments[0], kSequence_Precedence);
601 this->write(", ");
602 this->writeExpression(*arguments[1], kSequence_Precedence);
603 this->write(")");
604 }
605 break;
606 }
607 case kDot_SpecialIntrinsic: {
608 if (arguments[0]->type().columns() == 1) {
609 this->write("(");
610 this->writeExpression(*arguments[0], kMultiplicative_Precedence);
611 this->write(" * ");
612 this->writeExpression(*arguments[1], kMultiplicative_Precedence);
613 this->write(")");
614 } else {
615 this->write("dot(");
616 this->writeExpression(*arguments[0], kSequence_Precedence);
617 this->write(", ");
618 this->writeExpression(*arguments[1], kSequence_Precedence);
619 this->write(")");
620 }
621 break;
622 }
John Stilesad0571f2020-12-10 18:03:10 -0500623 case kFaceforward_SpecialIntrinsic: {
624 if (arguments[0]->type().columns() == 1) {
625 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
626 this->write("((((");
627 this->writeExpression(*arguments[2], kSequence_Precedence);
628 this->write(") * (");
629 this->writeExpression(*arguments[1], kSequence_Precedence);
630 this->write(") < 0) ? 1 : -1) * (");
631 this->writeExpression(*arguments[0], kSequence_Precedence);
632 this->write("))");
633 } else {
634 this->write("faceforward(");
635 this->writeExpression(*arguments[0], kSequence_Precedence);
636 this->write(", ");
637 this->writeExpression(*arguments[1], kSequence_Precedence);
638 this->write(", ");
639 this->writeExpression(*arguments[2], kSequence_Precedence);
640 this->write(")");
641 }
642 break;
643 }
Brian Osman46787d52020-11-24 14:18:23 -0500644 case kLength_SpecialIntrinsic: {
645 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
646 this->writeExpression(*arguments[0], kSequence_Precedence);
647 this->write(")");
648 break;
649 }
650 case kNormalize_SpecialIntrinsic: {
651 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
652 this->writeExpression(*arguments[0], kSequence_Precedence);
653 this->write(")");
654 break;
655 }
John Stiles0063a9f2020-12-10 18:01:45 -0500656 case kBitcast_SpecialIntrinsic: {
657 this->write(this->getBitcastIntrinsic(c.type()));
658 this->write("(");
659 this->writeExpression(*arguments[0], kSequence_Precedence);
660 this->write(")");
661 break;
662 }
John Stilese2d34f82020-12-10 18:02:02 -0500663 case kDegrees_SpecialIntrinsic: {
664 this->write("((");
665 this->writeExpression(*arguments[0], kSequence_Precedence);
666 this->write(") * 57.2957795)");
667 break;
668 }
669 case kRadians_SpecialIntrinsic: {
670 this->write("((");
671 this->writeExpression(*arguments[0], kSequence_Precedence);
672 this->write(") * 0.0174532925)");
673 break;
674 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400675 default:
676 ABORT("unsupported special intrinsic kind");
677 }
678}
679
John Stilesfcf8cb22020-08-06 14:29:22 -0400680// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
681// Cells that don't exist in the source matrix will be populated with identity-matrix values.
682void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
683 SkASSERT(rows <= 4);
684 SkASSERT(columns <= 4);
685
686 const char* columnSeparator = "";
687 for (int c = 0; c < columns; ++c) {
688 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
689 columnSeparator = "), ";
690
691 // Determine how many values to take from the source matrix for this row.
692 int swizzleLength = 0;
693 if (c < sourceMatrix.columns()) {
694 swizzleLength = std::min<>(rows, sourceMatrix.rows());
695 }
696
697 // Emit all the values from the source matrix row.
698 bool firstItem;
699 switch (swizzleLength) {
700 case 0: firstItem = true; break;
701 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
702 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
703 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
704 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
705 default: SkUNREACHABLE;
706 }
707
708 // Emit the placeholder identity-matrix cells.
709 for (int r = swizzleLength; r < rows; ++r) {
710 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
711 firstItem = false;
712 }
713 }
714
715 fExtraFunctions.writeText(")");
716}
717
718// Assembles a matrix of type floatRxC by concatenating an arbitrary mix of values, named `x0`,
719// `x1`, etc. An error is written if the expression list don't contain exactly R*C scalars.
John Stiles8e3b6be2020-10-13 11:14:08 -0400720void MetalCodeGenerator::assembleMatrixFromExpressions(const ExpressionArray& args,
721 int rows, int columns) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400722 size_t argIndex = 0;
723 int argPosition = 0;
724
725 const char* columnSeparator = "";
726 for (int c = 0; c < columns; ++c) {
727 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
728 columnSeparator = "), ";
729
730 const char* rowSeparator = "";
731 for (int r = 0; r < rows; ++r) {
732 fExtraFunctions.writeText(rowSeparator);
733 rowSeparator = ", ";
734
735 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400736 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400737 switch (argType.typeKind()) {
738 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400739 fExtraFunctions.printf("x%zu", argIndex);
740 break;
741 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400742 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400743 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
744 break;
745 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400746 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400747 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
748 argPosition / argType.rows(),
749 argPosition % argType.rows());
750 break;
751 }
752 default: {
753 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
754 fExtraFunctions.writeText("<error>");
755 break;
756 }
757 }
758
759 ++argPosition;
760 if (argPosition >= argType.columns() * argType.rows()) {
761 ++argIndex;
762 argPosition = 0;
763 }
764 } else {
765 SkDEBUGFAIL("not enough arguments for matrix constructor");
766 fExtraFunctions.writeText("<error>");
767 }
768 }
769 }
770
771 if (argPosition != 0 || argIndex != args.size()) {
772 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
773 fExtraFunctions.writeText(", <error>");
774 }
775
776 fExtraFunctions.writeText(")");
777}
778
John Stiles1bdafbf2020-05-28 12:17:20 -0400779// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
780// Keeps track of previously generated constructors so that we won't generate more than one
781// constructor for any given permutation of input argument types. Returns the name of the
782// generated constructor method.
783String MetalCodeGenerator::getMatrixConstructHelper(const Constructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400784 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500785 int columns = matrix.columns();
786 int rows = matrix.rows();
John Stiles8e3b6be2020-10-13 11:14:08 -0400787 const ExpressionArray& args = c.arguments();
John Stiles1bdafbf2020-05-28 12:17:20 -0400788
789 // Create the helper-method name and use it as our lookup key.
790 String name;
791 name.appendf("float%dx%d_from", columns, rows);
792 for (const std::unique_ptr<Expression>& expr : args) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400793 name.appendf("_%s", expr->type().displayName().c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400794 }
795
796 // If a helper-method has already been synthesized, we don't need to synthesize it again.
797 auto [iter, newlyCreated] = fHelpers.insert(name);
798 if (!newlyCreated) {
799 return name;
800 }
801
802 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
803 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
804 // supply a mixture of scalars and vectors.)
805 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
806
807 size_t argIndex = 0;
808 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400809 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400810 fExtraFunctions.printf("%s%s x%zu", argSeparator,
Ethan Nicholas30d30222020-09-11 12:27:26 -0400811 expr->type().displayName().c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400812 argSeparator = ", ";
813 }
814
815 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
816
John Stiles9aeed132020-11-24 17:36:06 -0500817 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400818 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400819 } else {
820 this->assembleMatrixFromExpressions(args, rows, columns);
John Stiles1bdafbf2020-05-28 12:17:20 -0400821 }
822
John Stilesfcf8cb22020-08-06 14:29:22 -0400823 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500824 return name;
825}
826
827bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
828 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
829 return false;
830 }
831 if (t1.columns() > 1) {
832 return this->canCoerce(t1.componentType(), t2.componentType());
833 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500834 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500835}
836
John Stiles1bdafbf2020-05-28 12:17:20 -0400837bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const Constructor& c) {
838 // A matrix construct helper is only necessary if we are, in fact, constructing a matrix.
John Stiles9aeed132020-11-24 17:36:06 -0500839 if (!c.type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400840 return false;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500841 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400842
843 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
844 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
845 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
846 // scalars can be constructed trivially. In more complex cases, we generate a helper function
847 // that converts our inputs into a properly-shaped matrix.
848 // A matrix construct helper method is always used if any input argument is a matrix.
849 // Helper methods are also necessary when any argument would span multiple rows. For instance:
850 //
851 // float2 x = (1, 2);
852 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
853 // | 2 4 6 |
854 //
855 // float2 x = (2, 3);
856 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
857 // | 2 4 6 |
858 //
859 // float4 x = (1, 2, 3, 4);
860 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
861 // | 2 4 |
862 //
863
864 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400865 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400866 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500867 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400868 return true;
869 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400870 position += expr->type().columns();
871 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400872 // An input argument would span multiple rows; a helper function is required.
873 return true;
874 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400875 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400876 // We've advanced to the end of a row. Wrap to the start of the next row.
877 position = 0;
878 }
879 }
880
881 return false;
882}
883
884void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400885 const Type& constructorType = c.type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400886 // Handle special cases for single-argument constructors.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400887 if (c.arguments().size() == 1) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400888 // If the type is coercible, emit it directly.
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400889 const Expression& arg = *c.arguments().front();
Ethan Nicholas30d30222020-09-11 12:27:26 -0400890 const Type& argType = arg.type();
891 if (this->canCoerce(constructorType, argType)) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400892 this->writeExpression(arg, parentPrecedence);
893 return;
894 }
895
896 // Metal supports creating matrices with a scalar on the diagonal via the single-argument
897 // matrix constructor.
John Stiles9aeed132020-11-24 17:36:06 -0500898 if (constructorType.isMatrix() && argType.isNumber()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400899 const Type& matrix = constructorType;
John Stiles1bdafbf2020-05-28 12:17:20 -0400900 this->write("float");
901 this->write(to_string(matrix.columns()));
902 this->write("x");
903 this->write(to_string(matrix.rows()));
904 this->write("(");
905 this->writeExpression(arg, parentPrecedence);
906 this->write(")");
907 return;
908 }
909 }
910
911 // Emit and invoke a matrix-constructor helper method if one is necessary.
912 if (this->matrixConstructHelperIsNeeded(c)) {
913 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +0000914 this->write("(");
915 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400916 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +0000917 this->write(separator);
918 separator = ", ";
John Stiles1bdafbf2020-05-28 12:17:20 -0400919 this->writeExpression(*expr, kSequence_Precedence);
John Stilesdaa573e2020-05-28 12:17:20 -0400920 }
John Stiles1fa15b12020-05-28 17:36:54 +0000921 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -0400922 return;
John Stilesdaa573e2020-05-28 12:17:20 -0400923 }
John Stiles1bdafbf2020-05-28 12:17:20 -0400924
925 // Explicitly invoke the constructor, passing in the necessary arguments.
John Stiles3dba3ee2020-12-02 23:35:49 -0500926 this->writeBaseType(constructorType);
927 this->disallowArrayTypes(constructorType); // constructors of array types aren't valid exprs
John Stiles1bdafbf2020-05-28 12:17:20 -0400928 this->write("(");
929 const char* separator = "";
930 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400931 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400932 const Type& argType = arg->type();
John Stiles1bdafbf2020-05-28 12:17:20 -0400933 this->write(separator);
934 separator = ", ";
John Stiles9aeed132020-11-24 17:36:06 -0500935 if (constructorType.isMatrix() &&
Ethan Nicholas30d30222020-09-11 12:27:26 -0400936 argType.columns() < constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400937 // Merge scalars and smaller vectors together.
938 if (!scalarCount) {
John Stiles3dba3ee2020-12-02 23:35:49 -0500939 this->writeBaseType(constructorType.componentType());
Ethan Nicholas30d30222020-09-11 12:27:26 -0400940 this->write(to_string(constructorType.rows()));
John Stiles1bdafbf2020-05-28 12:17:20 -0400941 this->write("(");
942 }
Ethan Nicholas30d30222020-09-11 12:27:26 -0400943 scalarCount += argType.columns();
John Stiles1bdafbf2020-05-28 12:17:20 -0400944 }
945 this->writeExpression(*arg, kSequence_Precedence);
Ethan Nicholas30d30222020-09-11 12:27:26 -0400946 if (scalarCount && scalarCount == constructorType.rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400947 this->write(")");
948 scalarCount = 0;
949 }
950 }
951 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -0400952}
953
954void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400955 if (fRTHeightName.length()) {
956 this->write("float4(_fragCoord.x, ");
957 this->write(fRTHeightName.c_str());
958 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500959 } else {
960 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
961 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400962}
963
964void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -0500965 // When assembling out-param helper functions, we copy variables into local clones with matching
966 // names. We never want to prepend "_in." or "_globals->" when writing these variables since
967 // we're actually targeting the clones.
968 if (fIgnoreVariableReferenceModifiers) {
969 this->writeName(ref.variable()->name());
970 return;
971 }
972
Ethan Nicholas78686922020-10-08 06:46:27 -0400973 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400974 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400975 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400976 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400977 case SK_FRAGCOORD_BUILTIN:
978 this->writeFragCoord();
979 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400980 case SK_VERTEXID_BUILTIN:
981 this->write("sk_VertexID");
982 break;
983 case SK_INSTANCEID_BUILTIN:
984 this->write("sk_InstanceID");
985 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400986 case SK_CLOCKWISE_BUILTIN:
987 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -0400988 // clockwise to match Skia convention.
Timothy Liang7b8875d2018-08-10 09:42:31 -0400989 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
990 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400991 default:
Ethan Nicholas78686922020-10-08 06:46:27 -0400992 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -0400993 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -0400994 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400995 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -0400996 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400997 this->write("_out->");
Ethan Nicholas78686922020-10-08 06:46:27 -0400998 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
999 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001000 this->write("_uniforms.");
1001 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -04001002 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -04001003 }
1004 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001005 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001006 }
1007}
1008
1009void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001010 this->writeExpression(*expr.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001011 this->write("[");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001012 this->writeExpression(*expr.index(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001013 this->write("]");
1014}
1015
1016void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001017 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1018 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
1019 this->writeExpression(*f.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001020 this->write(".");
1021 }
Timothy Liang7d637782018-06-05 09:58:07 -04001022 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001023 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001024 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001025 break;
1026 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001027 if (field->fName == "sk_PointSize") {
1028 this->write("_out->sk_PointSize");
1029 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001030 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04001031 this->write("_globals->");
1032 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1033 this->write("->");
1034 }
Timothy Liang651286f2018-06-07 09:55:33 -04001035 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001036 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001037 }
1038}
1039
1040void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001041 this->writeExpression(*swizzle.base(), kPostfix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001042 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001043 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001044 SkASSERT(c >= 0 && c <= 3);
1045 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001046 }
1047}
1048
1049MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
1050 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001051 case Token::Kind::TK_STAR: // fall through
1052 case Token::Kind::TK_SLASH: // fall through
1053 case Token::Kind::TK_PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
1054 case Token::Kind::TK_PLUS: // fall through
1055 case Token::Kind::TK_MINUS: return MetalCodeGenerator::kAdditive_Precedence;
1056 case Token::Kind::TK_SHL: // fall through
1057 case Token::Kind::TK_SHR: return MetalCodeGenerator::kShift_Precedence;
1058 case Token::Kind::TK_LT: // fall through
1059 case Token::Kind::TK_GT: // fall through
1060 case Token::Kind::TK_LTEQ: // fall through
1061 case Token::Kind::TK_GTEQ: return MetalCodeGenerator::kRelational_Precedence;
1062 case Token::Kind::TK_EQEQ: // fall through
1063 case Token::Kind::TK_NEQ: return MetalCodeGenerator::kEquality_Precedence;
1064 case Token::Kind::TK_BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
1065 case Token::Kind::TK_BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
1066 case Token::Kind::TK_BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
1067 case Token::Kind::TK_LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
1068 case Token::Kind::TK_LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
1069 case Token::Kind::TK_LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
1070 case Token::Kind::TK_EQ: // fall through
1071 case Token::Kind::TK_PLUSEQ: // fall through
1072 case Token::Kind::TK_MINUSEQ: // fall through
1073 case Token::Kind::TK_STAREQ: // fall through
1074 case Token::Kind::TK_SLASHEQ: // fall through
1075 case Token::Kind::TK_PERCENTEQ: // fall through
1076 case Token::Kind::TK_SHLEQ: // fall through
1077 case Token::Kind::TK_SHREQ: // fall through
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001078 case Token::Kind::TK_BITWISEANDEQ: // fall through
1079 case Token::Kind::TK_BITWISEXOREQ: // fall through
1080 case Token::Kind::TK_BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
1081 case Token::Kind::TK_COMMA: return MetalCodeGenerator::kSequence_Precedence;
Ethan Nicholascc305772017-10-13 16:17:45 -04001082 default: ABORT("unsupported binary operator");
1083 }
1084}
1085
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001086void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1087 const Type& result) {
1088 String key = "TimesEqual" + left.name() + right.name();
1089 if (fHelpers.find(key) == fHelpers.end()) {
1090 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
1091 " left = left * right;\n"
1092 " return left;\n"
Ethan Nicholase2c49992020-10-05 11:49:11 -04001093 "}", String(result.name()).c_str(), String(left.name()).c_str(),
1094 String(right.name()).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001095 }
1096}
1097
Ethan Nicholascc305772017-10-13 16:17:45 -04001098void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1099 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001100 const Expression& left = *b.left();
1101 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001102 const Type& leftType = left.type();
1103 const Type& rightType = right.type();
1104 Token::Kind op = b.getOperator();
1105 Precedence precedence = GetBinaryPrecedence(b.getOperator());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001106 bool needParens = precedence >= parentPrecedence;
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001107 switch (op) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001108 case Token::Kind::TK_EQEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001109 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001110 this->write("all");
1111 needParens = true;
1112 }
1113 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001114 case Token::Kind::TK_NEQ:
John Stiles9aeed132020-11-24 17:36:06 -05001115 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001116 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001117 needParens = true;
1118 }
1119 break;
1120 default:
1121 break;
1122 }
1123 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001124 this->write("(");
1125 }
John Stiles9aeed132020-11-24 17:36:06 -05001126 if (op == Token::Kind::TK_STAREQ && leftType.isMatrix() && rightType.isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001127 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001128 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001129 this->writeExpression(left, precedence);
1130 if (op != Token::Kind::TK_EQ && Compiler::IsAssignment(op) &&
1131 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001132 // This doesn't compile in Metal:
1133 // float4 x = float4(1);
1134 // x.xy *= float2x2(...);
1135 // with the error message "non-const reference cannot bind to vector element",
1136 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1137 // as long as the LHS has no side effects, and hope for the best otherwise.
1138 this->write(" = ");
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001139 this->writeExpression(left, kAssignment_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001140 this->write(" ");
John Stilesd6449e92020-11-30 09:13:23 -05001141 String opName = OperatorName(op);
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001142 SkASSERT(opName.endsWith("="));
1143 this->write(opName.substr(0, opName.size() - 1).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -04001144 this->write(" ");
1145 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001146 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001147 }
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001148 this->writeExpression(right, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001149 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001150 this->write(")");
1151 }
1152}
1153
1154void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1155 Precedence parentPrecedence) {
1156 if (kTernary_Precedence >= parentPrecedence) {
1157 this->write("(");
1158 }
Ethan Nicholasdd218162020-10-08 05:48:01 -04001159 this->writeExpression(*t.test(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001160 this->write(" ? ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001161 this->writeExpression(*t.ifTrue(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001162 this->write(" : ");
Ethan Nicholasdd218162020-10-08 05:48:01 -04001163 this->writeExpression(*t.ifFalse(), kTernary_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001164 if (kTernary_Precedence >= parentPrecedence) {
1165 this->write(")");
1166 }
1167}
1168
1169void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1170 Precedence parentPrecedence) {
1171 if (kPrefix_Precedence >= parentPrecedence) {
1172 this->write("(");
1173 }
John Stilesd6449e92020-11-30 09:13:23 -05001174 this->write(OperatorName(p.getOperator()));
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001175 this->writeExpression(*p.operand(), kPrefix_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001176 if (kPrefix_Precedence >= parentPrecedence) {
1177 this->write(")");
1178 }
1179}
1180
1181void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1182 Precedence parentPrecedence) {
1183 if (kPostfix_Precedence >= parentPrecedence) {
1184 this->write("(");
1185 }
Ethan Nicholas444ccc62020-10-09 10:16:22 -04001186 this->writeExpression(*p.operand(), kPostfix_Precedence);
John Stilesd6449e92020-11-30 09:13:23 -05001187 this->write(OperatorName(p.getOperator()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001188 if (kPostfix_Precedence >= parentPrecedence) {
1189 this->write(")");
1190 }
1191}
1192
1193void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001194 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001195}
1196
1197void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
Ethan Nicholas30d30222020-09-11 12:27:26 -04001198 if (i.type() == *fContext.fUInt_Type) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001199 this->write(to_string(i.value() & 0xffffffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001200 } else {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001201 this->write(to_string((int32_t) i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001202 }
1203}
1204
1205void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001206 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001207}
1208
1209void MetalCodeGenerator::writeSetting(const Setting& s) {
1210 ABORT("internal error; setting was not folded to a constant during compilation\n");
1211}
1212
John Stiles06b84ef2020-12-09 12:35:48 -05001213void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1214 const char*& separator) {
1215 Requirements requirements = this->requirements(f);
1216 if (requirements & kInputs_Requirement) {
1217 this->write(separator);
1218 this->write("_in");
1219 separator = ", ";
1220 }
1221 if (requirements & kOutputs_Requirement) {
1222 this->write(separator);
1223 this->write("_out");
1224 separator = ", ";
1225 }
1226 if (requirements & kUniforms_Requirement) {
1227 this->write(separator);
1228 this->write("_uniforms");
1229 separator = ", ";
1230 }
1231 if (requirements & kGlobals_Requirement) {
1232 this->write(separator);
1233 this->write("_globals");
1234 separator = ", ";
1235 }
1236 if (requirements & kFragCoord_Requirement) {
1237 this->write(separator);
1238 this->write("_fragCoord");
1239 separator = ", ";
1240 }
1241}
1242
1243void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1244 const char*& separator) {
1245 Requirements requirements = this->requirements(f);
1246 if (requirements & kInputs_Requirement) {
1247 this->write(separator);
1248 this->write("Inputs _in");
1249 separator = ", ";
1250 }
1251 if (requirements & kOutputs_Requirement) {
1252 this->write(separator);
1253 this->write("thread Outputs* _out");
1254 separator = ", ";
1255 }
1256 if (requirements & kUniforms_Requirement) {
1257 this->write(separator);
1258 this->write("Uniforms _uniforms");
1259 separator = ", ";
1260 }
1261 if (requirements & kGlobals_Requirement) {
1262 this->write(separator);
1263 this->write("thread Globals* _globals");
1264 separator = ", ";
1265 }
1266 if (requirements & kFragCoord_Requirement) {
1267 this->write(separator);
1268 this->write("float4 _fragCoord");
1269 separator = ", ";
1270 }
1271}
1272
John Stiles569249b2020-11-03 12:18:22 -05001273bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -04001274 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001275 const char* separator = "";
John Stiles569249b2020-11-03 12:18:22 -05001276 if ("main" == f.name()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001277 switch (fProgram.fKind) {
1278 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001279 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001280 break;
1281 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001282 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001283 break;
1284 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001285 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001286 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001287 }
1288 this->write("(Inputs _in [[stage_in]]");
1289 if (-1 != fUniformBuffer) {
1290 this->write(", constant Uniforms& _uniforms [[buffer(" +
1291 to_string(fUniformBuffer) + ")]]");
1292 }
Brian Osman133724c2020-10-28 14:14:39 -04001293 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001294 if (e->is<GlobalVarDeclaration>()) {
1295 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001296 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1297 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1298 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001299 fErrors.error(decls.fOffset,
1300 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001301 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001302 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001303 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001304 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001305 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001306 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001307 }
1308 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001309 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001310 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001311 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001312 this->write(")]]");
1313 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001314 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001315 this->write(SAMPLER_SUFFIX);
1316 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001317 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001318 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001319 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001320 } else if (e->is<InterfaceBlock>()) {
1321 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001322 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001323 continue;
1324 }
John Stilesbc3c41b2020-12-04 10:52:40 -05001325 if (intf.variable().modifiers().fLayout.fBinding < 0) {
1326 fErrors.error(intf.fOffset,
1327 "Metal interface blocks must have 'layout(binding=...)'");
1328 return false;
1329 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001330 this->write(", constant ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001331 this->writeBaseType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001332 this->write("& " );
1333 this->write(fInterfaceBlockNameMap[&intf]);
1334 this->write(" [[buffer(");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001335 this->write(to_string(intf.variable().modifiers().fLayout.fBinding));
Timothy Lianga06f2152018-05-24 15:33:31 -04001336 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001337 }
1338 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -05001339 if (fProgram.fKind == Program::kFragment_Kind) {
1340 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001341 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Ethan Nicholasf931e402019-07-26 15:40:33 -04001342 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -04001343 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001344 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001345 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -04001346 } else if (fProgram.fKind == Program::kVertex_Kind) {
1347 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001348 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001349 separator = ", ";
1350 } else {
John Stiles3dba3ee2020-12-02 23:35:49 -05001351 this->writeBaseType(f.returnType());
1352 this->disallowArrayTypes(f.returnType()); // return types can't be arrays in SkSL/GLSL
Timothy Liang651286f2018-06-07 09:55:33 -04001353 this->write(" ");
John Stiles569249b2020-11-03 12:18:22 -05001354 this->writeName(f.name());
Timothy Liang651286f2018-06-07 09:55:33 -04001355 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001356 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001357 }
John Stiles569249b2020-11-03 12:18:22 -05001358 for (const auto& param : f.parameters()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001359 this->write(separator);
1360 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -05001361 this->writeModifiers(param->modifiers(), /*globalContext=*/false);
Ethan Nicholas30d30222020-09-11 12:27:26 -04001362 const Type* type = &param->type();
John Stiles3dba3ee2020-12-02 23:35:49 -05001363 this->writeBaseType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001364 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001365 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001366 }
Timothy Liang651286f2018-06-07 09:55:33 -04001367 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001368 this->writeName(param->name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001369 this->writeArrayDimensions(*type);
Ethan Nicholascc305772017-10-13 16:17:45 -04001370 }
John Stiles569249b2020-11-03 12:18:22 -05001371 this->write(")");
1372 return true;
1373}
Ethan Nicholascc305772017-10-13 16:17:45 -04001374
John Stiles569249b2020-11-03 12:18:22 -05001375void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1376 this->writeFunctionDeclaration(f.declaration());
1377 this->writeLine(";");
1378}
1379
John Stiles986c7fb2020-12-01 14:44:56 -05001380static bool is_block_ending_with_return(const Statement* stmt) {
1381 // This function detects (potentially nested) blocks that end in a return statement.
1382 if (!stmt->is<Block>()) {
1383 return false;
1384 }
1385 const StatementArray& block = stmt->as<Block>().children();
1386 for (int index = block.count(); index--; ) {
1387 const Statement& stmt = *block[index];
1388 if (stmt.is<ReturnStatement>()) {
1389 return true;
1390 }
1391 if (stmt.is<Block>()) {
1392 return is_block_ending_with_return(&stmt);
1393 }
1394 if (!stmt.is<Nop>()) {
1395 break;
1396 }
1397 }
1398 return false;
1399}
1400
John Stiles569249b2020-11-03 12:18:22 -05001401void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001402 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001403
John Stiles569249b2020-11-03 12:18:22 -05001404 if (!this->writeFunctionDeclaration(f.declaration())) {
1405 return;
1406 }
1407
John Stiles986c7fb2020-12-01 14:44:56 -05001408 fCurrentFunction = &f.declaration();
1409 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1410
John Stiles569249b2020-11-03 12:18:22 -05001411 this->writeLine(" {");
1412
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04001413 if (f.declaration().name() == "main") {
John Stilescdcdb042020-07-06 09:03:51 -04001414 this->writeGlobalInit();
Timothy Liang7d637782018-06-05 09:58:07 -04001415 this->writeLine(" Outputs _outputStruct;");
1416 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001417 }
John Stilesc67b3622020-05-28 17:53:13 -04001418
Ethan Nicholascc305772017-10-13 16:17:45 -04001419 fFunctionHeader = "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001420 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001421 {
1422 AutoOutputStream outputToBuffer(this, &buffer);
1423 fIndentation++;
1424 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1425 if (!stmt->isEmpty()) {
1426 this->writeStatement(*stmt);
1427 this->writeLine();
1428 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001429 }
John Stiles44532372020-12-07 12:33:55 -05001430 if (f.declaration().name() == "main") {
1431 // If the main function doesn't end with a return, we need to synthesize one here.
1432 if (!is_block_ending_with_return(f.body().get())) {
1433 this->writeReturnStatementFromMain();
1434 this->writeLine("");
1435 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001436 }
John Stiles44532372020-12-07 12:33:55 -05001437 fIndentation--;
1438 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001439 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001440 this->write(fFunctionHeader);
1441 this->write(buffer.str());
1442}
1443
1444void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
John Stiles06b84ef2020-12-09 12:35:48 -05001445 bool globalContext) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001446 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1447 this->write("thread ");
1448 }
1449 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001450 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001451 }
1452}
1453
1454void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001455 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001456 return;
1457 }
John Stiles06b84ef2020-12-09 12:35:48 -05001458 this->writeModifiers(intf.variable().modifiers(), /*globalContext=*/true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001459 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001460 this->writeLine(intf.typeName() + " {");
1461 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001462 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001463 structType = &structType->componentType();
1464 }
John Stiles3dba3ee2020-12-02 23:35:49 -05001465 fWrittenStructs.push_back(structType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001466 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001467 this->writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001468 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001469 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001470 }
1471 fIndentation--;
1472 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001473 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001474 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001475 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001476 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001477 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001478 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001479 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001480 } else if (intf.arraySize() == Type::kUnsizedArray){
1481 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001482 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001483 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001484 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001485 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001486 }
1487 this->writeLine(";");
1488}
1489
Timothy Liangdc89f192018-06-13 09:20:31 -04001490void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1491 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001492 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001493 int currentOffset = 0;
1494 for (const auto& field: fields) {
1495 int fieldOffset = field.fModifiers.fLayout.fOffset;
1496 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001497 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001498 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1499 return;
1500 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001501 if (fieldOffset != -1) {
1502 if (currentOffset > fieldOffset) {
1503 fErrors.error(parentOffset,
1504 "offset of field '" + field.fName + "' must be at least " +
1505 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001506 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001507 } else if (currentOffset < fieldOffset) {
1508 this->write("char pad");
1509 this->write(to_string(fPaddingCount++));
1510 this->write("[");
1511 this->write(to_string(fieldOffset - currentOffset));
1512 this->writeLine("];");
1513 currentOffset = fieldOffset;
1514 }
1515 int alignment = memoryLayout.alignment(*fieldType);
1516 if (fieldOffset % alignment) {
1517 fErrors.error(parentOffset,
1518 "offset of field '" + field.fName + "' must be a multiple of " +
1519 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001520 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001521 }
1522 }
Brian Osman8609a242020-09-08 14:01:49 -04001523 size_t fieldSize = memoryLayout.size(*fieldType);
1524 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1525 fErrors.error(parentOffset, "field offset overflow");
1526 return;
1527 }
1528 currentOffset += fieldSize;
John Stiles06b84ef2020-12-09 12:35:48 -05001529 this->writeModifiers(field.fModifiers, /*globalContext=*/false);
John Stiles3dba3ee2020-12-02 23:35:49 -05001530 this->writeBaseType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001531 this->write(" ");
1532 this->writeName(field.fName);
John Stiles3dba3ee2020-12-02 23:35:49 -05001533 this->writeArrayDimensions(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001534 this->writeLine(";");
1535 if (parentIntf) {
1536 fInterfaceBlockMap[&field] = parentIntf;
1537 }
1538 }
1539}
1540
Ethan Nicholascc305772017-10-13 16:17:45 -04001541void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1542 this->writeExpression(value, kTopLevel_Precedence);
1543}
1544
Timothy Liang651286f2018-06-07 09:55:33 -04001545void MetalCodeGenerator::writeName(const String& name) {
1546 if (fReservedWords.find(name) != fReservedWords.end()) {
1547 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1548 }
1549 this->write(name);
1550}
1551
Brian Osmanc0213602020-10-06 14:43:32 -04001552void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& var, bool global) {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001553 if (global && !(var.var().modifiers().fFlags & Modifiers::kConst_Flag)) {
Brian Osmanc0213602020-10-06 14:43:32 -04001554 return;
Ethan Nicholascc305772017-10-13 16:17:45 -04001555 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001556 this->writeModifiers(var.var().modifiers(), global);
John Stiles3dba3ee2020-12-02 23:35:49 -05001557 this->writeBaseType(var.baseType());
1558 this->disallowArrayTypes(var.baseType()); // `float[2] x` shouldn't be possible (invalid SkSL)
Brian Osmanc0213602020-10-06 14:43:32 -04001559 this->write(" ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001560 this->writeName(var.var().name());
John Stiles62a56462020-12-03 10:41:58 -05001561 if (var.arraySize() > 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001562 this->write("[");
John Stiles62a56462020-12-03 10:41:58 -05001563 this->write(to_string(var.arraySize()));
Brian Osmanc0213602020-10-06 14:43:32 -04001564 this->write("]");
John Stiles62a56462020-12-03 10:41:58 -05001565 } else if (var.arraySize() == Type::kUnsizedArray){
1566 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001567 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001568 if (var.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001569 this->write(" = ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001570 this->writeVarInitializer(var.var(), *var.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001571 }
1572 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001573}
1574
1575void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001576 switch (s.kind()) {
1577 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001578 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001579 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001580 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04001581 this->writeExpression(*s.as<ExpressionStatement>().expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001582 this->write(";");
1583 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001584 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001585 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001586 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001587 case Statement::Kind::kVarDeclaration:
1588 this->writeVarDeclaration(s.as<VarDeclaration>(), false);
Ethan Nicholascc305772017-10-13 16:17:45 -04001589 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001590 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001591 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001592 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001593 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001594 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001595 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001596 case Statement::Kind::kWhile:
John Stiles26f98502020-08-18 09:30:51 -04001597 this->writeWhileStatement(s.as<WhileStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001598 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001599 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001600 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001601 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001602 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001603 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001604 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001605 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001606 this->write("break;");
1607 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001608 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001609 this->write("continue;");
1610 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001611 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001612 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001613 break;
John Stiles98c1f822020-09-09 14:18:53 -04001614 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001615 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001616 this->write(";");
1617 break;
1618 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001619#ifdef SK_DEBUG
Ethan Nicholascc305772017-10-13 16:17:45 -04001620 ABORT("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001621#endif
1622 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001623 }
1624}
1625
Ethan Nicholascc305772017-10-13 16:17:45 -04001626void MetalCodeGenerator::writeBlock(const Block& b) {
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001627 bool isScope = b.isScope();
1628 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001629 this->writeLine("{");
1630 fIndentation++;
1631 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001632 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1633 if (!stmt->isEmpty()) {
1634 this->writeStatement(*stmt);
1635 this->writeLine();
1636 }
1637 }
1638 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001639 fIndentation--;
1640 this->write("}");
1641 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001642}
1643
1644void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1645 this->write("if (");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001646 this->writeExpression(*stmt.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001647 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001648 this->writeStatement(*stmt.ifTrue());
1649 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001650 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001651 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04001652 }
1653}
1654
1655void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1656 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001657 if (f.initializer() && !f.initializer()->isEmpty()) {
1658 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04001659 } else {
1660 this->write("; ");
1661 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001662 if (f.test()) {
1663 this->writeExpression(*f.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001664 }
1665 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001666 if (f.next()) {
1667 this->writeExpression(*f.next(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001668 }
1669 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04001670 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001671}
1672
1673void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1674 this->write("while (");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001675 this->writeExpression(*w.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001676 this->write(") ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001677 this->writeStatement(*w.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001678}
1679
1680void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1681 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001682 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04001683 this->write(" while (");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04001684 this->writeExpression(*d.test(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001685 this->write(");");
1686}
1687
1688void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1689 this->write("switch (");
Ethan Nicholas01b05e52020-10-22 15:53:41 -04001690 this->writeExpression(*s.value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001691 this->writeLine(") {");
1692 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001693 for (const std::unique_ptr<SwitchCase>& c : s.cases()) {
1694 if (c->value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001695 this->write("case ");
John Stiles2d4f9592020-10-30 10:29:12 -04001696 this->writeExpression(*c->value(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001697 this->writeLine(":");
1698 } else {
1699 this->writeLine("default:");
1700 }
1701 fIndentation++;
John Stiles2d4f9592020-10-30 10:29:12 -04001702 for (const auto& stmt : c->statements()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001703 this->writeStatement(*stmt);
1704 this->writeLine();
1705 }
1706 fIndentation--;
1707 }
1708 fIndentation--;
1709 this->write("}");
1710}
1711
John Stiles986c7fb2020-12-01 14:44:56 -05001712void MetalCodeGenerator::writeReturnStatementFromMain() {
1713 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
1714 switch (fProgram.fKind) {
1715 case Program::kFragment_Kind:
1716 this->write("return *_out;");
1717 break;
1718 case Program::kVertex_Kind:
1719 this->write("return (_out->sk_Position.y = -_out->sk_Position.y, *_out);");
1720 break;
1721 default:
1722 SkDEBUGFAIL("unsupported kind of program");
1723 }
1724}
1725
Ethan Nicholascc305772017-10-13 16:17:45 -04001726void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stiles986c7fb2020-12-01 14:44:56 -05001727 if (fCurrentFunction && fCurrentFunction->name() == "main") {
1728 if (r.expression()) {
1729 fErrors.error(r.fOffset, "Metal does not support returning values from main()");
1730 }
1731 this->writeReturnStatementFromMain();
1732 return;
1733 }
1734
Ethan Nicholascc305772017-10-13 16:17:45 -04001735 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001736 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001737 this->write(" ");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04001738 this->writeExpression(*r.expression(), kTopLevel_Precedence);
Ethan Nicholascc305772017-10-13 16:17:45 -04001739 }
1740 this->write(";");
1741}
1742
1743void MetalCodeGenerator::writeHeader() {
1744 this->write("#include <metal_stdlib>\n");
1745 this->write("#include <simd/simd.h>\n");
1746 this->write("using namespace metal;\n");
1747}
1748
1749void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04001750 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001751 if (e->is<GlobalVarDeclaration>()) {
1752 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001753 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001754 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04001755 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001756 if (-1 == fUniformBuffer) {
1757 this->write("struct Uniforms {\n");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001758 fUniformBuffer = var.modifiers().fLayout.fSet;
Ethan Nicholascc305772017-10-13 16:17:45 -04001759 if (-1 == fUniformBuffer) {
1760 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1761 }
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001762 } else if (var.modifiers().fLayout.fSet != fUniformBuffer) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001763 if (-1 == fUniformBuffer) {
1764 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1765 "the same 'layout(set=...)'");
1766 }
1767 }
1768 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001769 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001770 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001771 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001772 this->writeArrayDimensions(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001773 this->write(";\n");
1774 }
1775 }
1776 }
1777 if (-1 != fUniformBuffer) {
1778 this->write("};\n");
1779 }
1780}
1781
1782void MetalCodeGenerator::writeInputStruct() {
1783 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04001784 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001785 if (e->is<GlobalVarDeclaration>()) {
1786 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001787 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001788 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
1789 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001790 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001791 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001792 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001793 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001794 this->writeArrayDimensions(var.type());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001795 if (-1 != var.modifiers().fLayout.fLocation) {
Brian Osmanc0213602020-10-06 14:43:32 -04001796 if (fProgram.fKind == Program::kVertex_Kind) {
1797 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001798 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001799 } else if (fProgram.fKind == Program::kFragment_Kind) {
1800 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001801 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001802 }
1803 }
1804 this->write(";\n");
1805 }
1806 }
1807 }
1808 this->write("};\n");
1809}
1810
1811void MetalCodeGenerator::writeOutputStruct() {
1812 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001813 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001814 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001815 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001816 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001817 }
Brian Osman133724c2020-10-28 14:14:39 -04001818 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001819 if (e->is<GlobalVarDeclaration>()) {
1820 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001821 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001822 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
1823 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001824 this->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001825 this->writeBaseType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04001826 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04001827 this->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001828 this->writeArrayDimensions(var.type());
John Stiles842b3592020-12-01 10:36:37 -05001829
1830 int location = var.modifiers().fLayout.fLocation;
1831 if (location < 0) {
1832 fErrors.error(var.fOffset,
1833 "Metal out variables must have 'layout(location=...)'");
1834 } else if (fProgram.fKind == Program::kVertex_Kind) {
1835 this->write(" [[user(locn" + to_string(location) + ")]]");
Brian Osmanc0213602020-10-06 14:43:32 -04001836 } else if (fProgram.fKind == Program::kFragment_Kind) {
John Stiles842b3592020-12-01 10:36:37 -05001837 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001838 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04001839 if (colorIndex) {
1840 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04001841 }
Brian Osmanc0213602020-10-06 14:43:32 -04001842 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001843 }
1844 this->write(";\n");
1845 }
1846 }
Timothy Liang7d637782018-06-05 09:58:07 -04001847 }
1848 if (fProgram.fKind == Program::kVertex_Kind) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04001849 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001850 }
1851 this->write("};\n");
1852}
1853
1854void MetalCodeGenerator::writeInterfaceBlocks() {
1855 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04001856 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001857 if (e->is<InterfaceBlock>()) {
1858 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04001859 wroteInterfaceBlock = true;
1860 }
1861 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001862 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001863 this->writeLine("struct sksl_synthetic_uniforms {");
1864 this->writeLine(" float u_skRTHeight;");
1865 this->writeLine("};");
1866 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001867}
1868
John Stilesdc75a972020-11-25 16:24:55 -05001869void MetalCodeGenerator::writeStructDefinitions() {
1870 for (const ProgramElement* e : fProgram.elements()) {
1871 if (e->is<StructDefinition>()) {
1872 if (this->writeStructDefinition(e->as<StructDefinition>().type())) {
1873 this->writeLine(";");
1874 }
1875 } else if (e->is<GlobalVarDeclaration>()) {
1876 // If a global var declaration introduces a struct type, we need to write that type
1877 // here, since globals are all embedded in a sub-struct.
1878 const Type* type = &e->as<GlobalVarDeclaration>().declaration()
1879 ->as<VarDeclaration>().baseType();
John Stilesc0c51062020-12-03 17:16:29 -05001880 if (type->isStruct()) {
John Stilesdc75a972020-11-25 16:24:55 -05001881 if (this->writeStructDefinition(*type)) {
1882 this->writeLine(";");
1883 }
1884 }
1885 }
1886 }
1887}
1888
John Stilescdcdb042020-07-06 09:03:51 -04001889void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
1890 // Visit the interface blocks.
1891 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05001892 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04001893 }
Brian Osman133724c2020-10-28 14:14:39 -04001894 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001895 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04001896 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04001897 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001898 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
1899 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
1900 const Variable& var = decl.var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001901 if ((!var.modifiers().fFlags && -1 == var.modifiers().fLayout.fBuiltin) ||
Brian Osmanc0213602020-10-06 14:43:32 -04001902 var.type().typeKind() == Type::TypeKind::kSampler) {
1903 if (var.type().typeKind() == Type::TypeKind::kSampler) {
1904 // Samplers are represented as a "texture/sampler" duo in the global struct.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001905 visitor->visitTexture(var.type(), var.name());
1906 visitor->visitSampler(var.type(), String(var.name()) + SAMPLER_SUFFIX);
Brian Osmanc0213602020-10-06 14:43:32 -04001907 } else {
1908 // Visit a regular variable.
John Stilesfdb8dbe2020-12-04 11:00:03 -05001909 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04001910 }
1911 }
1912 }
John Stilescdcdb042020-07-06 09:03:51 -04001913}
1914
1915void MetalCodeGenerator::writeGlobalStruct() {
1916 class : public GlobalStructVisitor {
1917 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001918 void visitInterfaceBlock(const InterfaceBlock& block, const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001919 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001920 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001921 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04001922 fCodeGen->write("* ");
1923 fCodeGen->writeName(blockName);
1924 fCodeGen->write(";\n");
1925 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001926 void visitTexture(const Type& type, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001927 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001928 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001929 fCodeGen->writeBaseType(type);
John Stilescdcdb042020-07-06 09:03:51 -04001930 fCodeGen->write(" ");
1931 fCodeGen->writeName(name);
John Stiles3dba3ee2020-12-02 23:35:49 -05001932 fCodeGen->writeArrayDimensions(type);
John Stilescdcdb042020-07-06 09:03:51 -04001933 fCodeGen->write(";\n");
1934 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001935 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001936 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001937 fCodeGen->write(" sampler ");
1938 fCodeGen->writeName(name);
1939 fCodeGen->write(";\n");
1940 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001941 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001942 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001943 fCodeGen->write(" ");
John Stiles3dba3ee2020-12-02 23:35:49 -05001944 fCodeGen->writeBaseType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001945 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001946 fCodeGen->writeName(var.name());
John Stiles3dba3ee2020-12-02 23:35:49 -05001947 fCodeGen->writeArrayDimensions(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04001948 fCodeGen->write(";\n");
1949 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001950 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04001951 if (fFirst) {
1952 fCodeGen->write("struct Globals {\n");
1953 fFirst = false;
1954 }
1955 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001956 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04001957 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05001958 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04001959 fFirst = true;
1960 }
1961 }
1962
1963 MetalCodeGenerator* fCodeGen = nullptr;
1964 bool fFirst = true;
1965 } visitor;
1966
1967 visitor.fCodeGen = this;
1968 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05001969 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04001970}
1971
1972void MetalCodeGenerator::writeGlobalInit() {
1973 class : public GlobalStructVisitor {
1974 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05001975 void visitInterfaceBlock(const InterfaceBlock& blockType,
John Stilescdcdb042020-07-06 09:03:51 -04001976 const String& blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001977 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001978 fCodeGen->write("&");
1979 fCodeGen->writeName(blockName);
1980 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001981 void visitTexture(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001982 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001983 fCodeGen->writeName(name);
1984 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001985 void visitSampler(const Type&, const String& name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001986 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001987 fCodeGen->writeName(name);
1988 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05001989 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05001990 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04001991 if (value) {
1992 fCodeGen->writeVarInitializer(var, *value);
1993 } else {
1994 fCodeGen->write("{}");
1995 }
1996 }
John Stiles83f3b8d2020-12-07 17:52:25 -05001997 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04001998 if (fFirst) {
1999 fCodeGen->write(" Globals globalStruct{");
2000 fFirst = false;
2001 } else {
2002 fCodeGen->write(", ");
2003 }
2004 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002005 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002006 if (!fFirst) {
2007 fCodeGen->writeLine("};");
2008 fCodeGen->writeLine(" thread Globals* _globals = &globalStruct;");
2009 fCodeGen->writeLine(" (void)_globals;");
2010 }
2011 }
2012 MetalCodeGenerator* fCodeGen = nullptr;
2013 bool fFirst = true;
2014 } visitor;
2015
2016 visitor.fCodeGen = this;
2017 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002018 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002019}
2020
Ethan Nicholascc305772017-10-13 16:17:45 -04002021void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002022 switch (e.kind()) {
2023 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002024 break;
Brian Osmanc0213602020-10-06 14:43:32 -04002025 case ProgramElement::Kind::kGlobalVar: {
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002026 const GlobalVarDeclaration& global = e.as<GlobalVarDeclaration>();
2027 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2028 int builtin = decl.var().modifiers().fLayout.fBuiltin;
Brian Osmanc0213602020-10-06 14:43:32 -04002029 if (-1 == builtin) {
2030 // normal var
2031 this->writeVarDeclaration(decl, true);
2032 this->writeLine();
2033 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
2034 // ignore
Ethan Nicholascc305772017-10-13 16:17:45 -04002035 }
2036 break;
2037 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002038 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002039 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002040 break;
John Stilesdc75a972020-11-25 16:24:55 -05002041 case ProgramElement::Kind::kStructDefinition:
2042 // Handled in writeStructDefinitions. Do nothing.
2043 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002044 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002045 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002046 break;
John Stiles569249b2020-11-03 12:18:22 -05002047 case ProgramElement::Kind::kFunctionPrototype:
2048 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2049 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002050 case ProgramElement::Kind::kModifiers:
John Stiles06b84ef2020-12-09 12:35:48 -05002051 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers(),
2052 /*globalContext=*/true);
Ethan Nicholascc305772017-10-13 16:17:45 -04002053 this->writeLine(";");
2054 break;
John Stiles712fd6b2020-11-25 22:25:43 -05002055 case ProgramElement::Kind::kEnum:
2056 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002057 default:
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002058#ifdef SK_DEBUG
2059 ABORT("unsupported program element: %s\n", e.description().c_str());
2060#endif
2061 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002062 }
2063}
2064
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002065MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2066 if (!e) {
2067 return kNo_Requirements;
2068 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002069 switch (e->kind()) {
2070 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002071 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002072 Requirements result = this->requirements(f.function());
2073 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002074 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002075 }
2076 return result;
2077 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002078 case Expression::Kind::kConstructor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002079 const Constructor& c = e->as<Constructor>();
Ethan Nicholascc305772017-10-13 16:17:45 -04002080 Requirements result = kNo_Requirements;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04002081 for (const auto& arg : c.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002082 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002083 }
2084 return result;
2085 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002086 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002087 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002088 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002089 return kGlobals_Requirement;
2090 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002091 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002092 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002093 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002094 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002095 case Expression::Kind::kBinary: {
2096 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002097 return this->requirements(bin.left().get()) |
2098 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002099 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002100 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002101 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002102 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002103 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002104 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002105 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002106 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002107 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002108 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002109 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002110 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2111 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002112 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002113 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002114 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002115 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002116 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002117 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002118 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002119 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002120 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002121 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002122 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002123 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002124 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002125 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002126 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002127 } else {
2128 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002129 }
2130 }
2131 return result;
2132 }
2133 default:
2134 return kNo_Requirements;
2135 }
2136}
2137
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002138MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2139 if (!s) {
2140 return kNo_Requirements;
2141 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002142 switch (s->kind()) {
2143 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002144 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002145 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002146 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002147 }
2148 return result;
2149 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002150 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002151 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002152 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002153 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002154 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002155 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002156 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002157 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002158 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002159 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002160 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002161 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002162 return this->requirements(i.test().get()) |
2163 this->requirements(i.ifTrue().get()) |
2164 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002165 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002166 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002167 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002168 return this->requirements(f.initializer().get()) |
2169 this->requirements(f.test().get()) |
2170 this->requirements(f.next().get()) |
2171 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002172 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002173 case Statement::Kind::kWhile: {
John Stiles3dc0da62020-08-19 17:48:31 -04002174 const WhileStatement& w = s->as<WhileStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002175 return this->requirements(w.test().get()) |
2176 this->requirements(w.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002177 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002178 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002179 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002180 return this->requirements(d.test().get()) |
2181 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002182 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002183 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002184 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002185 Requirements result = this->requirements(sw.value().get());
John Stiles2d4f9592020-10-30 10:29:12 -04002186 for (const std::unique_ptr<SwitchCase>& sc : sw.cases()) {
2187 for (const auto& st : sc->statements()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002188 result |= this->requirements(st.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002189 }
2190 }
2191 return result;
2192 }
2193 default:
2194 return kNo_Requirements;
2195 }
2196}
2197
2198MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002199 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002200 return kNo_Requirements;
2201 }
2202 auto found = fRequirements.find(&f);
2203 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002204 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002205 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002206 if (e->is<FunctionDefinition>()) {
2207 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002208 if (&def.declaration() == &f) {
2209 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002210 fRequirements[&f] = reqs;
2211 return reqs;
2212 }
2213 }
2214 }
John Stiles569249b2020-11-03 12:18:22 -05002215 // We never found a definition for this declared function, but it's legal to prototype a
2216 // function without ever giving a definition, as long as you don't call it.
2217 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002218 }
2219 return found->second;
2220}
2221
Timothy Liangb8eeb802018-07-23 16:46:16 -04002222bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04002223 fProgramKind = fProgram.fKind;
Ethan Nicholascc305772017-10-13 16:17:45 -04002224
John Stiles44532372020-12-07 12:33:55 -05002225 StringStream header;
2226 {
2227 AutoOutputStream outputToHeader(this, &header, &fIndentation);
2228 this->writeHeader();
2229 this->writeStructDefinitions();
2230 this->writeUniformStruct();
2231 this->writeInputStruct();
2232 this->writeOutputStruct();
2233 this->writeInterfaceBlocks();
2234 this->writeGlobalStruct();
2235 }
2236 StringStream body;
2237 {
2238 AutoOutputStream outputToBody(this, &body, &fIndentation);
2239 for (const ProgramElement* e : fProgram.elements()) {
2240 this->writeProgramElement(*e);
2241 }
2242 }
2243 write_stringstream(header, *fOut);
2244 write_stringstream(fExtraFunctions, *fOut);
2245 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002246 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002247}
2248
John Stilesa6841be2020-08-06 14:11:56 -04002249} // namespace SkSL