blob: c6d24e0c2cd4aea59cdd895853c6aba4280ee6df [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
John Stiles3738ef52021-04-13 10:41:57 -04008#include "src/sksl/codegen/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
John Stiles986c7fb2020-12-01 14:44:56 -050010#include "src/core/SkScopeExit.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/sksl/SkSLCompiler.h"
John Stiles0023c0c2020-11-16 13:32:18 -050012#include "src/sksl/SkSLMemoryLayout.h"
John Stiles7384b372021-04-01 13:48:15 -040013#include "src/sksl/ir/SkSLConstructorArray.h"
John Stiles8cad6372021-04-07 12:31:13 -040014#include "src/sksl/ir/SkSLConstructorCompoundCast.h"
John Stiles7384b372021-04-01 13:48:15 -040015#include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
John Stiles5abb9e12021-04-06 13:47:19 -040016#include "src/sksl/ir/SkSLConstructorMatrixResize.h"
John Stiles2938eea2021-04-01 18:58:25 -040017#include "src/sksl/ir/SkSLConstructorSplat.h"
John Stilesd47330f2021-04-08 23:25:52 -040018#include "src/sksl/ir/SkSLConstructorStruct.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050019#include "src/sksl/ir/SkSLExpressionStatement.h"
20#include "src/sksl/ir/SkSLExtension.h"
21#include "src/sksl/ir/SkSLIndexExpression.h"
22#include "src/sksl/ir/SkSLModifiersDeclaration.h"
23#include "src/sksl/ir/SkSLNop.h"
John Stilesdc75a972020-11-25 16:24:55 -050024#include "src/sksl/ir/SkSLStructDefinition.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050025#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040026
Brian Osmanc262a122020-08-06 16:34:34 -040027#include <algorithm>
28
Ethan Nicholascc305772017-10-13 16:17:45 -040029namespace SkSL {
30
John Stiles45990502021-02-16 10:55:27 -050031const char* MetalCodeGenerator::OperatorName(Operator op) {
32 switch (op.kind()) {
John Stilesd6449e92020-11-30 09:13:23 -050033 case Token::Kind::TK_LOGICALXOR: return "!=";
John Stiles45990502021-02-16 10:55:27 -050034 default: return op.operatorName();
John Stilesd6449e92020-11-30 09:13:23 -050035 }
36}
37
John Stilescdcdb042020-07-06 09:03:51 -040038class MetalCodeGenerator::GlobalStructVisitor {
39public:
40 virtual ~GlobalStructVisitor() = default;
Ethan Nicholas962dec42021-06-10 13:06:39 -040041 virtual void visitInterfaceBlock(const InterfaceBlock& block, skstd::string_view blockName) = 0;
42 virtual void visitTexture(const Type& type, skstd::string_view name) = 0;
43 virtual void visitSampler(const Type& type, skstd::string_view name) = 0;
John Stilesfdb8dbe2020-12-04 11:00:03 -050044 virtual void visitVariable(const Variable& var, const Expression* value) = 0;
John Stilescdcdb042020-07-06 09:03:51 -040045};
46
Ethan Nicholas962dec42021-06-10 13:06:39 -040047void MetalCodeGenerator::write(skstd::string_view s) {
Ethan Nicholasd2e09602021-06-10 11:21:59 -040048 if (s.empty()) {
Ethan Nicholascc305772017-10-13 16:17:45 -040049 return;
50 }
51 if (fAtLineStart) {
52 for (int i = 0; i < fIndentation; i++) {
53 fOut->writeText(" ");
54 }
55 }
Ethan Nicholasd2e09602021-06-10 11:21:59 -040056 fOut->writeText(String(s).c_str());
Ethan Nicholascc305772017-10-13 16:17:45 -040057 fAtLineStart = false;
58}
59
Ethan Nicholas962dec42021-06-10 13:06:39 -040060void MetalCodeGenerator::writeLine(skstd::string_view s) {
Ethan Nicholascc305772017-10-13 16:17:45 -040061 this->write(s);
John Stilese8b5a732021-03-12 13:25:52 -050062 fOut->writeText(fLineEnding);
63 fAtLineStart = true;
64}
65
66void MetalCodeGenerator::finishLine() {
67 if (!fAtLineStart) {
68 this->writeLine();
69 }
Ethan Nicholascc305772017-10-13 16:17:45 -040070}
71
72void MetalCodeGenerator::writeExtension(const Extension& ext) {
Ethan Nicholasefb09e22020-09-30 10:17:00 -040073 this->writeLine("#extension " + ext.name() + " : enable");
Ethan Nicholascc305772017-10-13 16:17:45 -040074}
75
Ethan Nicholas45fa8102020-01-13 10:58:49 -050076String MetalCodeGenerator::typeName(const Type& type) {
Ethan Nicholase6592142020-09-08 10:22:09 -040077 switch (type.typeKind()) {
John Stilesb4418502021-02-04 10:57:08 -050078 case Type::TypeKind::kArray:
79 SkASSERTF(type.columns() > 0, "invalid array size: %s", type.description().c_str());
80 return String::printf("array<%s, %d>",
81 this->typeName(type.componentType()).c_str(), type.columns());
82
Ethan Nicholase6592142020-09-08 10:22:09 -040083 case Type::TypeKind::kVector:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050084 return this->typeName(type.componentType()) + to_string(type.columns());
John Stilesb4418502021-02-04 10:57:08 -050085
Ethan Nicholase6592142020-09-08 10:22:09 -040086 case Type::TypeKind::kMatrix:
Ethan Nicholas45fa8102020-01-13 10:58:49 -050087 return this->typeName(type.componentType()) + to_string(type.columns()) + "x" +
88 to_string(type.rows());
John Stilesb4418502021-02-04 10:57:08 -050089
Ethan Nicholase6592142020-09-08 10:22:09 -040090 case Type::TypeKind::kSampler:
John Stiles368db7c2020-12-29 11:20:08 -050091 return "texture2d<float>"; // FIXME - support other texture types
John Stilesb4418502021-02-04 10:57:08 -050092
Ethan Nicholascc305772017-10-13 16:17:45 -040093 default:
John Stiles54e7c052021-01-11 14:22:36 -050094 if (type == *fContext.fTypes.fHalf) {
Timothy Liang43d225f2018-07-19 15:27:13 -040095 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholasd2e09602021-06-10 11:21:59 -040096 return String(fContext.fTypes.fFloat->name());
Timothy Liang7d637782018-06-05 09:58:07 -040097 } else {
Ethan Nicholasd2e09602021-06-10 11:21:59 -040098 return String(type.name());
Timothy Liang7d637782018-06-05 09:58:07 -040099 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400100 }
101}
102
Brian Osman02bc5222021-01-28 11:00:20 -0500103void MetalCodeGenerator::writeStructDefinition(const StructDefinition& s) {
104 const Type& type = s.type();
John Stilesdc75a972020-11-25 16:24:55 -0500105 this->writeLine("struct " + type.name() + " {");
106 fIndentation++;
107 this->writeFields(type.fields(), type.fOffset);
108 fIndentation--;
Brian Osman02bc5222021-01-28 11:00:20 -0500109 this->writeLine("};");
John Stilesdc75a972020-11-25 16:24:55 -0500110}
111
John Stilesb4418502021-02-04 10:57:08 -0500112void MetalCodeGenerator::writeType(const Type& type) {
113 this->write(this->typeName(type));
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500114}
115
Ethan Nicholascc305772017-10-13 16:17:45 -0400116void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
Ethan Nicholase6592142020-09-08 10:22:09 -0400117 switch (expr.kind()) {
118 case Expression::Kind::kBinary:
John Stiles81365af2020-08-18 09:24:00 -0400119 this->writeBinaryExpression(expr.as<BinaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400120 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400121 case Expression::Kind::kBoolLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400122 this->writeBoolLiteral(expr.as<BoolLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400123 break;
John Stiles2bec8ab2021-04-06 18:40:04 -0400124 case Expression::Kind::kConstructorArray:
John Stilesd47330f2021-04-08 23:25:52 -0400125 case Expression::Kind::kConstructorStruct:
John Stiles2bec8ab2021-04-06 18:40:04 -0400126 this->writeAnyConstructor(expr.asAnyConstructor(), "{", "}", parentPrecedence);
127 break;
John Stiles8cad6372021-04-07 12:31:13 -0400128 case Expression::Kind::kConstructorCompound:
129 this->writeConstructorCompound(expr.as<ConstructorCompound>(), parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -0400130 break;
131 case Expression::Kind::kConstructorDiagonalMatrix:
132 case Expression::Kind::kConstructorSplat:
133 this->writeAnyConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400134 break;
John Stiles5abb9e12021-04-06 13:47:19 -0400135 case Expression::Kind::kConstructorMatrixResize:
136 this->writeConstructorMatrixResize(expr.as<ConstructorMatrixResize>(),
137 parentPrecedence);
138 break;
John Stilesfd7252f2021-04-04 22:24:40 -0400139 case Expression::Kind::kConstructorScalarCast:
John Stiles8cad6372021-04-07 12:31:13 -0400140 case Expression::Kind::kConstructorCompoundCast:
John Stilesb14a8192021-04-05 11:40:46 -0400141 this->writeCastConstructor(expr.asAnyConstructor(), "(", ")", parentPrecedence);
John Stiles2938eea2021-04-01 18:58:25 -0400142 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400143 case Expression::Kind::kIntLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400144 this->writeIntLiteral(expr.as<IntLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400145 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400146 case Expression::Kind::kFieldAccess:
John Stiles81365af2020-08-18 09:24:00 -0400147 this->writeFieldAccess(expr.as<FieldAccess>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400148 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400149 case Expression::Kind::kFloatLiteral:
John Stiles81365af2020-08-18 09:24:00 -0400150 this->writeFloatLiteral(expr.as<FloatLiteral>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400151 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400152 case Expression::Kind::kFunctionCall:
John Stiles81365af2020-08-18 09:24:00 -0400153 this->writeFunctionCall(expr.as<FunctionCall>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400154 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400155 case Expression::Kind::kPrefix:
John Stiles81365af2020-08-18 09:24:00 -0400156 this->writePrefixExpression(expr.as<PrefixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400157 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400158 case Expression::Kind::kPostfix:
John Stiles81365af2020-08-18 09:24:00 -0400159 this->writePostfixExpression(expr.as<PostfixExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400160 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400161 case Expression::Kind::kSetting:
John Stiles81365af2020-08-18 09:24:00 -0400162 this->writeSetting(expr.as<Setting>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400163 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400164 case Expression::Kind::kSwizzle:
John Stiles81365af2020-08-18 09:24:00 -0400165 this->writeSwizzle(expr.as<Swizzle>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400166 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400167 case Expression::Kind::kVariableReference:
John Stiles81365af2020-08-18 09:24:00 -0400168 this->writeVariableReference(expr.as<VariableReference>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400169 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400170 case Expression::Kind::kTernary:
John Stiles81365af2020-08-18 09:24:00 -0400171 this->writeTernaryExpression(expr.as<TernaryExpression>(), parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400172 break;
Ethan Nicholase6592142020-09-08 10:22:09 -0400173 case Expression::Kind::kIndex:
John Stiles81365af2020-08-18 09:24:00 -0400174 this->writeIndexExpression(expr.as<IndexExpression>());
Ethan Nicholascc305772017-10-13 16:17:45 -0400175 break;
176 default:
John Stileseada7bc2021-02-02 16:29:32 -0500177 SkDEBUGFAILF("unsupported expression: %s", expr.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -0500178 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400179 }
180}
181
John Stiles06b84ef2020-12-09 12:35:48 -0500182String MetalCodeGenerator::getOutParamHelper(const FunctionCall& call,
183 const ExpressionArray& arguments,
184 const SkTArray<VariableReference*>& outVars) {
185 AutoOutputStream outputToExtraFunctions(this, &fExtraFunctions, &fIndentation);
186 const FunctionDeclaration& function = call.function();
187
John Stilese1068342021-03-22 11:57:41 -0400188 String name = "_skOutParamHelper" + to_string(fSwizzleHelperCount++) +
189 "_" + function.mangledName();
John Stiles06b84ef2020-12-09 12:35:48 -0500190 const char* separator = "";
191
192 // Emit a prototype for the function we'll be calling through to in our helper.
193 if (!function.isBuiltin()) {
194 this->writeFunctionDeclaration(function);
195 this->writeLine(";");
196 }
197
198 // Synthesize a helper function that takes the same inputs as `function`, except in places where
199 // `outVars` is non-null; in those places, we take the type of the VariableReference.
200 //
201 // float _skOutParamHelper0_originalFuncName(float _var0, float _var1, float& outParam) {
John Stilesb4418502021-02-04 10:57:08 -0500202 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500203 this->write(" ");
204 this->write(name);
205 this->write("(");
206 this->writeFunctionRequirementParams(function, separator);
207
208 SkASSERT(outVars.size() == arguments.size());
209 SkASSERT(outVars.size() == function.parameters().size());
210
John Stiles73e2c892021-02-13 13:58:01 -0500211 // We need to detect cases where the caller passes the same variable as an out-param more than
212 // once, and avoid reusing the variable name. (In those cases we can actually just ignore the
213 // redundant input parameter entirely, and not give it any name.)
214 std::unordered_set<const Variable*> writtenVars;
215
John Stiles06b84ef2020-12-09 12:35:48 -0500216 for (int index = 0; index < arguments.count(); ++index) {
217 this->write(separator);
218 separator = ", ";
219
220 const Variable* param = function.parameters()[index];
Brian Osman58134e12021-05-13 14:51:07 -0400221 this->writeModifiers(param->modifiers());
John Stiles06b84ef2020-12-09 12:35:48 -0500222
223 const Type* type = outVars[index] ? &outVars[index]->type() : &arguments[index]->type();
John Stilesb4418502021-02-04 10:57:08 -0500224 this->writeType(*type);
John Stiles06b84ef2020-12-09 12:35:48 -0500225
226 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
227 this->write("&");
228 }
229 if (outVars[index]) {
John Stiles73e2c892021-02-13 13:58:01 -0500230 auto [iter, didInsert] = writtenVars.insert(outVars[index]->variable());
231 if (didInsert) {
232 this->write(" ");
233 fIgnoreVariableReferenceModifiers = true;
234 this->writeVariableReference(*outVars[index]);
235 fIgnoreVariableReferenceModifiers = false;
236 }
John Stiles06b84ef2020-12-09 12:35:48 -0500237 } else {
238 this->write(" _var");
239 this->write(to_string(index));
240 }
John Stiles06b84ef2020-12-09 12:35:48 -0500241 }
242 this->writeLine(") {");
243
244 ++fIndentation;
245 for (int index = 0; index < outVars.count(); ++index) {
246 if (!outVars[index]) {
247 continue;
248 }
249 // float3 _var2[ = outParam.zyx];
John Stilesb4418502021-02-04 10:57:08 -0500250 this->writeType(arguments[index]->type());
John Stiles06b84ef2020-12-09 12:35:48 -0500251 this->write(" _var");
252 this->write(to_string(index));
253
254 const Variable* param = function.parameters()[index];
255 if (param->modifiers().fFlags & Modifiers::kIn_Flag) {
256 this->write(" = ");
257 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500258 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500259 fIgnoreVariableReferenceModifiers = false;
260 }
261
262 this->writeLine(";");
263 }
264
John Stilesf7410bd2021-01-19 13:07:55 -0500265 // [int _skResult = ] myFunction(inputs, outputs, _globals, _var0, _var1, _var2, _var3);
John Stiles06b84ef2020-12-09 12:35:48 -0500266 bool hasResult = (call.type().name() != "void");
267 if (hasResult) {
John Stilesb4418502021-02-04 10:57:08 -0500268 this->writeType(call.type());
John Stiles06b84ef2020-12-09 12:35:48 -0500269 this->write(" _skResult = ");
270 }
271
John Stilese1068342021-03-22 11:57:41 -0400272 this->writeName(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500273 this->write("(");
274 separator = "";
275 this->writeFunctionRequirementArgs(function, separator);
276
277 for (int index = 0; index < arguments.count(); ++index) {
278 this->write(separator);
279 separator = ", ";
280
281 this->write("_var");
282 this->write(to_string(index));
283 }
284 this->writeLine(");");
285
286 for (int index = 0; index < outVars.count(); ++index) {
287 if (!outVars[index]) {
288 continue;
289 }
290 // outParam.zyx = _var2;
291 fIgnoreVariableReferenceModifiers = true;
Brian Osman00185012021-02-04 16:07:11 -0500292 this->writeExpression(*arguments[index], Precedence::kAssignment);
John Stiles06b84ef2020-12-09 12:35:48 -0500293 fIgnoreVariableReferenceModifiers = false;
294 this->write(" = _var");
295 this->write(to_string(index));
296 this->writeLine(";");
297 }
298
299 if (hasResult) {
300 this->writeLine("return _skResult;");
301 }
302
303 --fIndentation;
304 this->writeLine("}");
305
306 return name;
John Stilesb21fac22020-12-04 15:36:49 -0500307}
308
John Stilesf64e4072020-12-10 10:34:27 -0500309String MetalCodeGenerator::getBitcastIntrinsic(const Type& outType) {
310 return "as_type<" + outType.displayName() + ">";
311}
312
Ethan Nicholascc305772017-10-13 16:17:45 -0400313void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400314 const FunctionDeclaration& function = c.function();
John Stiles496b7d12021-05-06 10:26:45 -0400315
316 // Many intrinsics need to be rewritten in Metal.
317 if (function.isIntrinsic()) {
318 if (this->writeIntrinsicCall(c, function.intrinsicKind())) {
John Stiles89ac7c22020-12-30 17:47:31 -0500319 return;
320 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400321 }
John Stilesb21fac22020-12-04 15:36:49 -0500322
John Stilesd7199b22020-12-30 16:22:58 -0500323 // Determine whether or not we need to emulate GLSL's out-param semantics for Metal using a
324 // helper function. (Specifically, out-parameters in GLSL are only written back to the original
325 // variable at the end of the function call; also, swizzles are supported, whereas Metal doesn't
326 // allow a swizzle to be passed to a `floatN&`.)
327 const ExpressionArray& arguments = c.arguments();
John Stilesb21fac22020-12-04 15:36:49 -0500328 const std::vector<const Variable*>& parameters = function.parameters();
329 SkASSERT(arguments.size() == parameters.size());
John Stiles06b84ef2020-12-09 12:35:48 -0500330
331 bool foundOutParam = false;
332 SkSTArray<16, VariableReference*> outVars;
John Stilesf64e4072020-12-10 10:34:27 -0500333 outVars.push_back_n(arguments.count(), (VariableReference*)nullptr);
John Stiles06b84ef2020-12-09 12:35:48 -0500334
335 for (int index = 0; index < arguments.count(); ++index) {
John Stilesb21fac22020-12-04 15:36:49 -0500336 // If this is an out parameter...
337 if (parameters[index]->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stiles06b84ef2020-12-09 12:35:48 -0500338 // Find the expression's inner variable being written to.
John Stilesb21fac22020-12-04 15:36:49 -0500339 Analysis::AssignmentInfo info;
John Stiles06b84ef2020-12-09 12:35:48 -0500340 // Assignability was verified at IRGeneration time, so this should always succeed.
341 SkAssertResult(Analysis::IsAssignable(*arguments[index], &info));
342 outVars[index] = info.fAssignedVar;
343 foundOutParam = true;
John Stilesb21fac22020-12-04 15:36:49 -0500344 }
345 }
346
John Stiles06b84ef2020-12-09 12:35:48 -0500347 if (foundOutParam) {
348 // Out parameters need to be written back to at the end of the function. To do this, we
349 // synthesize a helper function which evaluates the out-param expression into a temporary
350 // variable, calls the original function, then writes the temp var back into the out param
351 // using the original out-param expression. (This lets us support things like swizzles and
352 // array indices.)
John Stilesd7199b22020-12-30 16:22:58 -0500353 this->write(getOutParamHelper(c, arguments, outVars));
354 } else {
John Stilese1068342021-03-22 11:57:41 -0400355 this->write(function.mangledName());
John Stiles06b84ef2020-12-09 12:35:48 -0500356 }
357
Ethan Nicholascc305772017-10-13 16:17:45 -0400358 this->write("(");
359 const char* separator = "";
John Stiles06b84ef2020-12-09 12:35:48 -0500360 this->writeFunctionRequirementArgs(function, separator);
361 for (int i = 0; i < arguments.count(); ++i) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400362 this->write(separator);
363 separator = ", ";
John Stiles06b84ef2020-12-09 12:35:48 -0500364
365 if (outVars[i]) {
Brian Osman00185012021-02-04 16:07:11 -0500366 this->writeExpression(*outVars[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500367 } else {
Brian Osman00185012021-02-04 16:07:11 -0500368 this->writeExpression(*arguments[i], Precedence::kSequence);
John Stiles06b84ef2020-12-09 12:35:48 -0500369 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400370 }
371 this->write(")");
372}
373
Brian Osman964f0a02020-12-29 10:15:22 -0500374static constexpr char kInverse2x2[] = R"(
375float2x2 float2x2_inverse(float2x2 m) {
376 return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));
377}
378)";
379
380static constexpr char kInverse3x3[] = R"(
381float3x3 float3x3_inverse(float3x3 m) {
382 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];
383 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];
384 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];
385 float b01 = a22*a11 - a12*a21;
386 float b11 = -a22*a10 + a12*a20;
387 float b21 = a21*a10 - a11*a20;
388 float det = a00*b01 + a01*b11 + a02*b21;
389 return float3x3(b01, (-a22*a01 + a02*a21), ( a12*a01 - a02*a11),
390 b11, ( a22*a00 - a02*a20), (-a12*a00 + a02*a10),
391 b21, (-a21*a00 + a01*a20), ( a11*a00 - a01*a10)) * (1/det);
392}
393)";
394
395static constexpr char kInverse4x4[] = R"(
396float4x4 float4x4_inverse(float4x4 m) {
397 float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];
398 float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];
399 float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];
400 float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];
401 float b00 = a00*a11 - a01*a10;
402 float b01 = a00*a12 - a02*a10;
403 float b02 = a00*a13 - a03*a10;
404 float b03 = a01*a12 - a02*a11;
405 float b04 = a01*a13 - a03*a11;
406 float b05 = a02*a13 - a03*a12;
407 float b06 = a20*a31 - a21*a30;
408 float b07 = a20*a32 - a22*a30;
409 float b08 = a20*a33 - a23*a30;
410 float b09 = a21*a32 - a22*a31;
411 float b10 = a21*a33 - a23*a31;
412 float b11 = a22*a33 - a23*a32;
413 float det = b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06;
414 return float4x4(a11*b11 - a12*b10 + a13*b09,
415 a02*b10 - a01*b11 - a03*b09,
416 a31*b05 - a32*b04 + a33*b03,
417 a22*b04 - a21*b05 - a23*b03,
418 a12*b08 - a10*b11 - a13*b07,
419 a00*b11 - a02*b08 + a03*b07,
420 a32*b02 - a30*b05 - a33*b01,
421 a20*b05 - a22*b02 + a23*b01,
422 a10*b10 - a11*b08 + a13*b06,
423 a01*b08 - a00*b10 - a03*b06,
424 a30*b04 - a31*b02 + a33*b00,
425 a21*b02 - a20*b04 - a23*b00,
426 a11*b07 - a10*b09 - a12*b06,
427 a00*b09 - a01*b07 + a02*b06,
428 a31*b01 - a30*b03 - a32*b00,
429 a20*b03 - a21*b01 + a22*b00) * (1/det);
430}
431)";
432
John Stilesd7199b22020-12-30 16:22:58 -0500433String MetalCodeGenerator::getInversePolyfill(const ExpressionArray& arguments) {
434 // Only use polyfills for a function taking a single-argument square matrix.
435 if (arguments.size() == 1) {
436 const Type& type = arguments.front()->type();
437 if (type.isMatrix() && type.rows() == type.columns()) {
438 // Inject the correct polyfill based on the matrix size.
439 String name = this->typeName(type) + "_inverse";
440 auto [iter, didInsert] = fWrittenIntrinsics.insert(name);
441 if (didInsert) {
442 switch (type.rows()) {
443 case 2:
444 fExtraFunctions.writeText(kInverse2x2);
445 break;
446 case 3:
447 fExtraFunctions.writeText(kInverse3x3);
448 break;
449 case 4:
450 fExtraFunctions.writeText(kInverse4x4);
451 break;
452 }
453 }
454 return name;
Chris Daltondba7aab2018-11-15 10:57:49 -0500455 }
456 }
John Stilesd7199b22020-12-30 16:22:58 -0500457 // This isn't the built-in `inverse`. We don't want to polyfill it at all.
458 return "inverse";
Chris Daltondba7aab2018-11-15 10:57:49 -0500459}
460
Brian Osman93aed9a2020-12-28 15:18:46 -0500461static constexpr char kMatrixCompMult[] = R"(
462template <int C, int R>
463matrix<float, C, R> matrixCompMult(matrix<float, C, R> a, matrix<float, C, R> b) {
464 matrix<float, C, R> result;
465 for (int c = 0; c < C; ++c) {
466 result[c] = a[c] * b[c];
467 }
468 return result;
469}
470)";
471
472void MetalCodeGenerator::writeMatrixCompMult() {
473 String name = "matrixCompMult";
474 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
475 fWrittenIntrinsics.insert(name);
476 fExtraFunctions.writeText(kMatrixCompMult);
477 }
478}
479
John Stiles86424eb2020-12-11 11:17:14 -0500480String MetalCodeGenerator::getTempVariable(const Type& type) {
481 String tempVar = "_skTemp" + to_string(fVarCount++);
482 this->fFunctionHeader += " " + this->typeName(type) + " " + tempVar + ";\n";
483 return tempVar;
484}
485
John Stiles791c27d2020-12-30 14:56:57 -0500486void MetalCodeGenerator::writeSimpleIntrinsic(const FunctionCall& c) {
487 // Write out an intrinsic function call exactly as-is. No muss no fuss.
488 this->write(c.function().name());
John Stilesd7199b22020-12-30 16:22:58 -0500489 this->writeArgumentList(c.arguments());
490}
491
492void MetalCodeGenerator::writeArgumentList(const ExpressionArray& arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500493 this->write("(");
494 const char* separator = "";
John Stilesd7199b22020-12-30 16:22:58 -0500495 for (const std::unique_ptr<Expression>& arg : arguments) {
John Stiles791c27d2020-12-30 14:56:57 -0500496 this->write(separator);
497 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -0500498 this->writeExpression(*arg, Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500499 }
500 this->write(")");
501}
502
John Stiles496b7d12021-05-06 10:26:45 -0400503bool MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c, IntrinsicKind kind) {
John Stiles8e3b6be2020-10-13 11:14:08 -0400504 const ExpressionArray& arguments = c.arguments();
Timothy Liang6403b0e2018-05-17 10:40:04 -0400505 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400506 case k_sample_IntrinsicKind: {
Brian Osman00185012021-02-04 16:07:11 -0500507 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400508 this->write(".sample(");
Brian Osman00185012021-02-04 16:07:11 -0500509 this->writeExpression(*arguments[0], Precedence::kSequence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400510 this->write(SAMPLER_SUFFIX);
511 this->write(", ");
Ethan Nicholas0dec9922020-10-05 15:51:52 -0400512 const Type& arg1Type = arguments[1]->type();
John Stilesb14a8192021-04-05 11:40:46 -0400513 if (arg1Type.columns() == 3) {
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500514 // have to store the vector in a temp variable to avoid double evaluating it
John Stiles86424eb2020-12-11 11:17:14 -0500515 String tmpVar = this->getTempVariable(arg1Type);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500516 this->write("(" + tmpVar + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500517 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500518 this->write(", " + tmpVar + ".xy / " + tmpVar + ".z))");
Timothy Liangee84fe12018-05-18 14:38:19 -0400519 } else {
John Stilesb14a8192021-04-05 11:40:46 -0400520 SkASSERT(arg1Type.columns() == 2);
Brian Osman00185012021-02-04 16:07:11 -0500521 this->writeExpression(*arguments[1], Precedence::kSequence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400522 this->write(")");
523 }
John Stiles496b7d12021-05-06 10:26:45 -0400524 return true;
Ethan Nicholas30d30222020-09-11 12:27:26 -0400525 }
John Stiles496b7d12021-05-06 10:26:45 -0400526 case k_mod_IntrinsicKind: {
Timothy Liang651286f2018-06-07 09:55:33 -0400527 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
John Stiles86424eb2020-12-11 11:17:14 -0500528 String tmpX = this->getTempVariable(arguments[0]->type());
John Stiles61b2e812020-12-30 18:27:31 -0500529 String tmpY = this->getTempVariable(arguments[1]->type());
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500530 this->write("(" + tmpX + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500531 this->writeExpression(*arguments[0], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500532 this->write(", " + tmpY + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500533 this->writeExpression(*arguments[1], Precedence::kSequence);
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500534 this->write(", " + tmpX + " - " + tmpY + " * floor(" + tmpX + " / " + tmpY + "))");
John Stiles496b7d12021-05-06 10:26:45 -0400535 return true;
Ethan Nicholas45fa8102020-01-13 10:58:49 -0500536 }
Brian Osman46787d52020-11-24 14:18:23 -0500537 // GLSL declares scalar versions of most geometric intrinsics, but these don't exist in MSL
John Stiles496b7d12021-05-06 10:26:45 -0400538 case k_distance_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500539 if (arguments[0]->type().columns() == 1) {
540 this->write("abs(");
Brian Osman00185012021-02-04 16:07:11 -0500541 this->writeExpression(*arguments[0], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500542 this->write(" - ");
Brian Osman00185012021-02-04 16:07:11 -0500543 this->writeExpression(*arguments[1], Precedence::kAdditive);
Brian Osman46787d52020-11-24 14:18:23 -0500544 this->write(")");
545 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500546 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500547 }
John Stiles496b7d12021-05-06 10:26:45 -0400548 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500549 }
John Stiles496b7d12021-05-06 10:26:45 -0400550 case k_dot_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500551 if (arguments[0]->type().columns() == 1) {
552 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500553 this->writeExpression(*arguments[0], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500554 this->write(" * ");
Brian Osman00185012021-02-04 16:07:11 -0500555 this->writeExpression(*arguments[1], Precedence::kMultiplicative);
Brian Osman46787d52020-11-24 14:18:23 -0500556 this->write(")");
557 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500558 this->writeSimpleIntrinsic(c);
Brian Osman46787d52020-11-24 14:18:23 -0500559 }
John Stiles496b7d12021-05-06 10:26:45 -0400560 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500561 }
John Stiles496b7d12021-05-06 10:26:45 -0400562 case k_faceforward_IntrinsicKind: {
John Stilesad0571f2020-12-10 18:03:10 -0500563 if (arguments[0]->type().columns() == 1) {
564 // ((((Nref) * (I) < 0) ? 1 : -1) * (N))
565 this->write("((((");
Brian Osman00185012021-02-04 16:07:11 -0500566 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500567 this->write(") * (");
Brian Osman00185012021-02-04 16:07:11 -0500568 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500569 this->write(") < 0) ? 1 : -1) * (");
Brian Osman00185012021-02-04 16:07:11 -0500570 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilesad0571f2020-12-10 18:03:10 -0500571 this->write("))");
572 } else {
John Stiles791c27d2020-12-30 14:56:57 -0500573 this->writeSimpleIntrinsic(c);
John Stilesad0571f2020-12-10 18:03:10 -0500574 }
John Stiles496b7d12021-05-06 10:26:45 -0400575 return true;
John Stilesad0571f2020-12-10 18:03:10 -0500576 }
John Stiles496b7d12021-05-06 10:26:45 -0400577 case k_length_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500578 this->write(arguments[0]->type().columns() == 1 ? "abs(" : "length(");
Brian Osman00185012021-02-04 16:07:11 -0500579 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500580 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400581 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500582 }
John Stiles496b7d12021-05-06 10:26:45 -0400583 case k_normalize_IntrinsicKind: {
Brian Osman46787d52020-11-24 14:18:23 -0500584 this->write(arguments[0]->type().columns() == 1 ? "sign(" : "normalize(");
Brian Osman00185012021-02-04 16:07:11 -0500585 this->writeExpression(*arguments[0], Precedence::kSequence);
Brian Osman46787d52020-11-24 14:18:23 -0500586 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400587 return true;
Brian Osman46787d52020-11-24 14:18:23 -0500588 }
John Stiles496b7d12021-05-06 10:26:45 -0400589
590 case k_floatBitsToInt_IntrinsicKind:
591 case k_floatBitsToUint_IntrinsicKind:
592 case k_intBitsToFloat_IntrinsicKind:
593 case k_uintBitsToFloat_IntrinsicKind: {
John Stiles0063a9f2020-12-10 18:01:45 -0500594 this->write(this->getBitcastIntrinsic(c.type()));
595 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500596 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles0063a9f2020-12-10 18:01:45 -0500597 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400598 return true;
John Stiles0063a9f2020-12-10 18:01:45 -0500599 }
John Stiles496b7d12021-05-06 10:26:45 -0400600 case k_degrees_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500601 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500602 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500603 this->write(") * 57.2957795)");
John Stiles496b7d12021-05-06 10:26:45 -0400604 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500605 }
John Stiles496b7d12021-05-06 10:26:45 -0400606 case k_radians_IntrinsicKind: {
John Stilese2d34f82020-12-10 18:02:02 -0500607 this->write("((");
Brian Osman00185012021-02-04 16:07:11 -0500608 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese2d34f82020-12-10 18:02:02 -0500609 this->write(") * 0.0174532925)");
John Stiles496b7d12021-05-06 10:26:45 -0400610 return true;
John Stilese2d34f82020-12-10 18:02:02 -0500611 }
John Stiles496b7d12021-05-06 10:26:45 -0400612 case k_dFdx_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500613 this->write("dfdx");
614 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400615 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500616 }
John Stiles496b7d12021-05-06 10:26:45 -0400617 case k_dFdy_IntrinsicKind: {
Brian Salomond8d85b92021-07-07 09:41:17 -0400618 this->write(fRTFlipName + ".y*dfdy");
John Stilesd7199b22020-12-30 16:22:58 -0500619 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400620 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500621 }
John Stiles496b7d12021-05-06 10:26:45 -0400622 case k_inverse_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500623 this->write(this->getInversePolyfill(arguments));
624 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400625 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500626 }
John Stiles496b7d12021-05-06 10:26:45 -0400627 case k_inversesqrt_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500628 this->write("rsqrt");
629 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400630 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500631 }
John Stiles496b7d12021-05-06 10:26:45 -0400632 case k_atan_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500633 this->write(c.arguments().size() == 2 ? "atan2" : "atan");
634 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400635 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500636 }
John Stiles496b7d12021-05-06 10:26:45 -0400637 case k_reflect_IntrinsicKind: {
John Stiles791c27d2020-12-30 14:56:57 -0500638 if (arguments[0]->type().columns() == 1) {
639 // We need to synthesize `I - 2 * N * I * N`.
640 String tmpI = this->getTempVariable(arguments[0]->type());
641 String tmpN = this->getTempVariable(arguments[1]->type());
642
643 // (_skTempI = ...
644 this->write("(" + tmpI + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500645 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500646
647 // , _skTempN = ...
648 this->write(", " + tmpN + " = ");
Brian Osman00185012021-02-04 16:07:11 -0500649 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles791c27d2020-12-30 14:56:57 -0500650
651 // , _skTempI - 2 * _skTempN * _skTempI * _skTempN)
652 this->write(", " + tmpI + " - 2 * " + tmpN + " * " + tmpI + " * " + tmpN + ")");
653 } else {
654 this->writeSimpleIntrinsic(c);
655 }
John Stiles496b7d12021-05-06 10:26:45 -0400656 return true;
John Stiles791c27d2020-12-30 14:56:57 -0500657 }
John Stiles496b7d12021-05-06 10:26:45 -0400658 case k_refract_IntrinsicKind: {
John Stiles4b783d62020-12-30 14:58:07 -0500659 if (arguments[0]->type().columns() == 1) {
660 // Metal does implement refract for vectors; rather than reimplementing refract from
661 // scratch, we can replace the call with `refract(float2(I,0), float2(N,0), eta).x`.
662 this->write("(refract(float2(");
Brian Osman00185012021-02-04 16:07:11 -0500663 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500664 this->write(", 0), float2(");
Brian Osman00185012021-02-04 16:07:11 -0500665 this->writeExpression(*arguments[1], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500666 this->write(", 0), ");
Brian Osman00185012021-02-04 16:07:11 -0500667 this->writeExpression(*arguments[2], Precedence::kSequence);
John Stiles4b783d62020-12-30 14:58:07 -0500668 this->write(").x)");
669 } else {
670 this->writeSimpleIntrinsic(c);
671 }
John Stiles496b7d12021-05-06 10:26:45 -0400672 return true;
John Stiles4b783d62020-12-30 14:58:07 -0500673 }
John Stiles496b7d12021-05-06 10:26:45 -0400674 case k_roundEven_IntrinsicKind: {
John Stiles23456532020-12-30 18:12:48 -0500675 this->write("rint");
676 this->writeArgumentList(c.arguments());
John Stiles496b7d12021-05-06 10:26:45 -0400677 return true;
John Stiles23456532020-12-30 18:12:48 -0500678 }
John Stiles496b7d12021-05-06 10:26:45 -0400679 case k_bitCount_IntrinsicKind: {
John Stilese7dc7cb2020-12-22 15:37:14 -0500680 this->write("popcount(");
Brian Osman00185012021-02-04 16:07:11 -0500681 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stilese7dc7cb2020-12-22 15:37:14 -0500682 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400683 return true;
John Stilese7dc7cb2020-12-22 15:37:14 -0500684 }
John Stiles496b7d12021-05-06 10:26:45 -0400685 case k_findLSB_IntrinsicKind: {
John Stiles86424eb2020-12-11 11:17:14 -0500686 // Create a temp variable to store the expression, to avoid double-evaluating it.
687 String skTemp = this->getTempVariable(arguments[0]->type());
688 String exprType = this->typeName(arguments[0]->type());
689
690 // ctz returns numbits(type) on zero inputs; GLSL documents it as generating -1 instead.
691 // Use select to detect zero inputs and force a -1 result.
692
693 // (_skTemp1 = (.....), select(ctz(_skTemp1), int4(-1), _skTemp1 == int4(0)))
694 this->write("(");
695 this->write(skTemp);
696 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500697 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles86424eb2020-12-11 11:17:14 -0500698 this->write("), select(ctz(");
699 this->write(skTemp);
700 this->write("), ");
701 this->write(exprType);
702 this->write("(-1), ");
703 this->write(skTemp);
704 this->write(" == ");
705 this->write(exprType);
706 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400707 return true;
John Stiles86424eb2020-12-11 11:17:14 -0500708 }
John Stiles496b7d12021-05-06 10:26:45 -0400709 case k_findMSB_IntrinsicKind: {
John Stiles9685e522020-12-14 11:52:14 -0500710 // Create a temp variable to store the expression, to avoid double-evaluating it.
711 String skTemp1 = this->getTempVariable(arguments[0]->type());
712 String exprType = this->typeName(arguments[0]->type());
713
714 // GLSL findMSB is actually quite different from Metal's clz:
715 // - For signed negative numbers, it returns the first zero bit, not the first one bit!
716 // - For an empty input (0/~0 depending on sign), findMSB gives -1; clz is numbits(type)
717
718 // (_skTemp1 = (.....),
719 this->write("(");
720 this->write(skTemp1);
721 this->write(" = (");
Brian Osman00185012021-02-04 16:07:11 -0500722 this->writeExpression(*arguments[0], Precedence::kSequence);
John Stiles9685e522020-12-14 11:52:14 -0500723 this->write("), ");
724
725 // Signed input types might be negative; we need another helper variable to negate the
726 // input (since we can only find one bits, not zero bits).
727 String skTemp2;
728 if (arguments[0]->type().isSigned()) {
729 // ... _skTemp2 = (select(_skTemp1, ~_skTemp1, _skTemp1 < 0)),
730 skTemp2 = this->getTempVariable(arguments[0]->type());
731 this->write(skTemp2);
732 this->write(" = (select(");
733 this->write(skTemp1);
734 this->write(", ~");
735 this->write(skTemp1);
736 this->write(", ");
737 this->write(skTemp1);
738 this->write(" < 0)), ");
739 } else {
740 skTemp2 = skTemp1;
741 }
742
743 // ... select(int4(clz(_skTemp2)), int4(-1), _skTemp2 == int4(0)))
744 this->write("select(");
745 this->write(this->typeName(c.type()));
746 this->write("(clz(");
747 this->write(skTemp2);
748 this->write(")), ");
749 this->write(this->typeName(c.type()));
750 this->write("(-1), ");
751 this->write(skTemp2);
752 this->write(" == ");
753 this->write(exprType);
754 this->write("(0)))");
John Stiles496b7d12021-05-06 10:26:45 -0400755 return true;
John Stiles9685e522020-12-14 11:52:14 -0500756 }
John Stiles496b7d12021-05-06 10:26:45 -0400757 case k_matrixCompMult_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500758 this->writeMatrixCompMult();
759 this->writeSimpleIntrinsic(c);
John Stiles496b7d12021-05-06 10:26:45 -0400760 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500761 }
John Stilescc2d9cc2021-07-09 17:38:41 -0400762 case k_mix_IntrinsicKind: {
763 SkASSERT(c.arguments().size() == 3);
764 if (arguments[2]->type().componentType().isBoolean()) {
765 // The Boolean forms of GLSL mix() use the select() intrinsic in Metal.
766 this->write("select");
767 this->writeArgumentList(c.arguments());
768 return true;
769 }
770 // The basic form of mix() is supported by Metal as-is.
771 this->writeSimpleIntrinsic(c);
772 return true;
773 }
John Stiles496b7d12021-05-06 10:26:45 -0400774 case k_equal_IntrinsicKind:
775 case k_greaterThan_IntrinsicKind:
776 case k_greaterThanEqual_IntrinsicKind:
777 case k_lessThan_IntrinsicKind:
778 case k_lessThanEqual_IntrinsicKind:
779 case k_notEqual_IntrinsicKind: {
John Stilesd7199b22020-12-30 16:22:58 -0500780 this->write("(");
Brian Osman00185012021-02-04 16:07:11 -0500781 this->writeExpression(*c.arguments()[0], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500782 switch (kind) {
John Stiles496b7d12021-05-06 10:26:45 -0400783 case k_equal_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500784 this->write(" == ");
785 break;
John Stiles496b7d12021-05-06 10:26:45 -0400786 case k_notEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500787 this->write(" != ");
788 break;
John Stiles496b7d12021-05-06 10:26:45 -0400789 case k_lessThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500790 this->write(" < ");
791 break;
John Stiles496b7d12021-05-06 10:26:45 -0400792 case k_lessThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500793 this->write(" <= ");
794 break;
John Stiles496b7d12021-05-06 10:26:45 -0400795 case k_greaterThan_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500796 this->write(" > ");
797 break;
John Stiles496b7d12021-05-06 10:26:45 -0400798 case k_greaterThanEqual_IntrinsicKind:
John Stilesd7199b22020-12-30 16:22:58 -0500799 this->write(" >= ");
800 break;
801 default:
John Stilesf57207b2021-02-02 17:50:34 -0500802 SK_ABORT("unsupported comparison intrinsic kind");
John Stilesd7199b22020-12-30 16:22:58 -0500803 }
Brian Osman00185012021-02-04 16:07:11 -0500804 this->writeExpression(*c.arguments()[1], Precedence::kRelational);
John Stilesd7199b22020-12-30 16:22:58 -0500805 this->write(")");
John Stiles496b7d12021-05-06 10:26:45 -0400806 return true;
John Stilesd7199b22020-12-30 16:22:58 -0500807 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400808 default:
John Stiles496b7d12021-05-06 10:26:45 -0400809 return false;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400810 }
811}
812
John Stilesfcf8cb22020-08-06 14:29:22 -0400813// Assembles a matrix of type floatRxC by resizing another matrix named `x0`.
814// Cells that don't exist in the source matrix will be populated with identity-matrix values.
815void MetalCodeGenerator::assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns) {
816 SkASSERT(rows <= 4);
817 SkASSERT(columns <= 4);
818
819 const char* columnSeparator = "";
820 for (int c = 0; c < columns; ++c) {
821 fExtraFunctions.printf("%sfloat%d(", columnSeparator, rows);
822 columnSeparator = "), ";
823
824 // Determine how many values to take from the source matrix for this row.
825 int swizzleLength = 0;
826 if (c < sourceMatrix.columns()) {
827 swizzleLength = std::min<>(rows, sourceMatrix.rows());
828 }
829
830 // Emit all the values from the source matrix row.
831 bool firstItem;
832 switch (swizzleLength) {
833 case 0: firstItem = true; break;
834 case 1: firstItem = false; fExtraFunctions.printf("x0[%d].x", c); break;
835 case 2: firstItem = false; fExtraFunctions.printf("x0[%d].xy", c); break;
836 case 3: firstItem = false; fExtraFunctions.printf("x0[%d].xyz", c); break;
837 case 4: firstItem = false; fExtraFunctions.printf("x0[%d].xyzw", c); break;
838 default: SkUNREACHABLE;
839 }
840
841 // Emit the placeholder identity-matrix cells.
842 for (int r = swizzleLength; r < rows; ++r) {
843 fExtraFunctions.printf("%s%s", firstItem ? "" : ", ", (r == c) ? "1.0" : "0.0");
844 firstItem = false;
845 }
846 }
847
848 fExtraFunctions.writeText(")");
849}
850
John Stiles1f7300b2021-07-08 15:40:38 -0400851// Assembles a matrix of type floatCxR by concatenating an arbitrary mix of values, named `x0`,
852// `x1`, etc. An error is written if the expression list don't contain exactly C*R scalars.
John Stiles5abb9e12021-04-06 13:47:19 -0400853void MetalCodeGenerator::assembleMatrixFromExpressions(const AnyConstructor& ctor,
John Stiles1f7300b2021-07-08 15:40:38 -0400854 int columns, int rows) {
John Stilesfcf8cb22020-08-06 14:29:22 -0400855 size_t argIndex = 0;
856 int argPosition = 0;
John Stiles5abb9e12021-04-06 13:47:19 -0400857 auto args = ctor.argumentSpan();
John Stilesfcf8cb22020-08-06 14:29:22 -0400858
John Stiles1f7300b2021-07-08 15:40:38 -0400859 const char* rowSeparator = "";
860 for (int r = 0; r < rows; ++r) {
861 fExtraFunctions.printf("%sfloat%d(", rowSeparator, rows);
862 rowSeparator = "), ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400863
John Stiles1f7300b2021-07-08 15:40:38 -0400864 const char* columnSeparator = "";
865 for (int c = 0; c < columns; ++c) {
866 fExtraFunctions.writeText(columnSeparator);
867 columnSeparator = ", ";
John Stilesfcf8cb22020-08-06 14:29:22 -0400868
869 if (argIndex < args.size()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400870 const Type& argType = args[argIndex]->type();
Ethan Nicholase6592142020-09-08 10:22:09 -0400871 switch (argType.typeKind()) {
872 case Type::TypeKind::kScalar: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400873 fExtraFunctions.printf("x%zu", argIndex);
874 break;
875 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400876 case Type::TypeKind::kVector: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400877 fExtraFunctions.printf("x%zu[%d]", argIndex, argPosition);
878 break;
879 }
Ethan Nicholase6592142020-09-08 10:22:09 -0400880 case Type::TypeKind::kMatrix: {
John Stilesfcf8cb22020-08-06 14:29:22 -0400881 fExtraFunctions.printf("x%zu[%d][%d]", argIndex,
882 argPosition / argType.rows(),
883 argPosition % argType.rows());
884 break;
885 }
886 default: {
887 SkDEBUGFAIL("incorrect type of argument for matrix constructor");
888 fExtraFunctions.writeText("<error>");
889 break;
890 }
891 }
892
893 ++argPosition;
894 if (argPosition >= argType.columns() * argType.rows()) {
895 ++argIndex;
896 argPosition = 0;
897 }
898 } else {
899 SkDEBUGFAIL("not enough arguments for matrix constructor");
900 fExtraFunctions.writeText("<error>");
901 }
902 }
903 }
904
905 if (argPosition != 0 || argIndex != args.size()) {
906 SkDEBUGFAIL("incorrect number of arguments for matrix constructor");
907 fExtraFunctions.writeText(", <error>");
908 }
909
910 fExtraFunctions.writeText(")");
911}
912
John Stiles1bdafbf2020-05-28 12:17:20 -0400913// Generates a constructor for 'matrix' which reorganizes the input arguments into the proper shape.
914// Keeps track of previously generated constructors so that we won't generate more than one
915// constructor for any given permutation of input argument types. Returns the name of the
916// generated constructor method.
John Stiles5abb9e12021-04-06 13:47:19 -0400917String MetalCodeGenerator::getMatrixConstructHelper(const AnyConstructor& c) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400918 const Type& matrix = c.type();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500919 int columns = matrix.columns();
920 int rows = matrix.rows();
John Stiles5abb9e12021-04-06 13:47:19 -0400921 auto args = c.argumentSpan();
John Stiles1bdafbf2020-05-28 12:17:20 -0400922
923 // Create the helper-method name and use it as our lookup key.
924 String name;
925 name.appendf("float%dx%d_from", columns, rows);
926 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles36129132020-12-29 12:28:04 -0500927 name.appendf("_%s", this->typeName(expr->type()).c_str());
John Stiles1bdafbf2020-05-28 12:17:20 -0400928 }
929
930 // If a helper-method has already been synthesized, we don't need to synthesize it again.
931 auto [iter, newlyCreated] = fHelpers.insert(name);
932 if (!newlyCreated) {
933 return name;
934 }
935
936 // Unlike GLSL, Metal requires that matrices are initialized with exactly R vectors of C
937 // components apiece. (In Metal 2.0, you can also supply R*C scalars, but you still cannot
938 // supply a mixture of scalars and vectors.)
939 fExtraFunctions.printf("float%dx%d %s(", columns, rows, name.c_str());
940
941 size_t argIndex = 0;
942 const char* argSeparator = "";
John Stilesfcf8cb22020-08-06 14:29:22 -0400943 for (const std::unique_ptr<Expression>& expr : args) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400944 fExtraFunctions.printf("%s%s x%zu", argSeparator,
John Stiles36129132020-12-29 12:28:04 -0500945 this->typeName(expr->type()).c_str(), argIndex++);
John Stiles1bdafbf2020-05-28 12:17:20 -0400946 argSeparator = ", ";
947 }
948
949 fExtraFunctions.printf(") {\n return float%dx%d(", columns, rows);
950
John Stiles9aeed132020-11-24 17:36:06 -0500951 if (args.size() == 1 && args.front()->type().isMatrix()) {
Ethan Nicholas30d30222020-09-11 12:27:26 -0400952 this->assembleMatrixFromMatrix(args.front()->type(), rows, columns);
John Stilesfcf8cb22020-08-06 14:29:22 -0400953 } else {
John Stiles1f7300b2021-07-08 15:40:38 -0400954 this->assembleMatrixFromExpressions(c, columns, rows);
John Stiles1bdafbf2020-05-28 12:17:20 -0400955 }
956
John Stilesfcf8cb22020-08-06 14:29:22 -0400957 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500958 return name;
959}
960
961bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
962 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
963 return false;
964 }
965 if (t1.columns() > 1) {
966 return this->canCoerce(t1.componentType(), t2.componentType());
967 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500968 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500969}
970
John Stiles8cad6372021-04-07 12:31:13 -0400971bool MetalCodeGenerator::matrixConstructHelperIsNeeded(const ConstructorCompound& c) {
John Stiles2bec8ab2021-04-06 18:40:04 -0400972 SkASSERT(c.type().isMatrix());
John Stiles1bdafbf2020-05-28 12:17:20 -0400973
974 // GLSL is fairly free-form about inputs to its matrix constructors, but Metal is not; it
975 // expects exactly R vectors of C components apiece. (Metal 2.0 also allows a list of R*C
976 // scalars.) Some cases are simple to translate and so we handle those inline--e.g. a list of
977 // scalars can be constructed trivially. In more complex cases, we generate a helper function
978 // that converts our inputs into a properly-shaped matrix.
979 // A matrix construct helper method is always used if any input argument is a matrix.
980 // Helper methods are also necessary when any argument would span multiple rows. For instance:
981 //
982 // float2 x = (1, 2);
983 // float3x2(x, 3, 4, 5, 6) = | 1 3 5 | = no helper needed; conversion can be done inline
984 // | 2 4 6 |
985 //
986 // float2 x = (2, 3);
987 // float3x2(1, x, 4, 5, 6) = | 1 3 5 | = x spans multiple rows; a helper method will be used
988 // | 2 4 6 |
989 //
990 // float4 x = (1, 2, 3, 4);
991 // float2x2(x) = | 1 3 | = x spans multiple rows; a helper method will be used
992 // | 2 4 |
993 //
994
995 int position = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -0400996 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400997 // If an input argument is a matrix, we need a helper function.
John Stiles9aeed132020-11-24 17:36:06 -0500998 if (expr->type().isMatrix()) {
John Stiles1bdafbf2020-05-28 12:17:20 -0400999 return true;
1000 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001001 position += expr->type().columns();
1002 if (position > c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001003 // An input argument would span multiple rows; a helper function is required.
1004 return true;
1005 }
Ethan Nicholas30d30222020-09-11 12:27:26 -04001006 if (position == c.type().rows()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001007 // We've advanced to the end of a row. Wrap to the start of the next row.
1008 position = 0;
1009 }
1010 }
1011
1012 return false;
1013}
1014
John Stiles5abb9e12021-04-06 13:47:19 -04001015void MetalCodeGenerator::writeConstructorMatrixResize(const ConstructorMatrixResize& c,
1016 Precedence parentPrecedence) {
1017 // Matrix-resize via casting doesn't natively exist in Metal at all, so we always need to use a
1018 // matrix-construct helper here.
1019 this->write(this->getMatrixConstructHelper(c));
1020 this->write("(");
1021 this->writeExpression(*c.argument(), Precedence::kSequence);
1022 this->write(")");
1023}
1024
John Stiles8cad6372021-04-07 12:31:13 -04001025void MetalCodeGenerator::writeConstructorCompound(const ConstructorCompound& c,
1026 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001027 if (c.type().isVector()) {
1028 this->writeConstructorCompoundVector(c, parentPrecedence);
1029 } else if (c.type().isMatrix()) {
John Stiles8cad6372021-04-07 12:31:13 -04001030 this->writeConstructorCompoundMatrix(c, parentPrecedence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001031 } else {
John Stiles6de2e1d2021-07-09 12:41:55 -04001032 fErrors.error(c.fOffset, "unsupported compound constructor");
John Stiles2bec8ab2021-04-06 18:40:04 -04001033 }
1034}
John Stiles7384b372021-04-01 13:48:15 -04001035
John Stiles6de2e1d2021-07-09 12:41:55 -04001036void MetalCodeGenerator::writeVectorFromMat2x2ConstructorHelper() {
1037 static constexpr char kCode[] =
1038R"(float4 float4_from_float2x2(float2x2 x) {
1039 return float4(x[0].xy, x[1].xy);
1040}
1041)";
1042
1043 String name = "matrixCompMult";
1044 if (fHelpers.find("float4_from_float2x2") == fHelpers.end()) {
1045 fHelpers.insert("float4_from_float2x2");
1046 fExtraFunctions.writeText(kCode);
1047 }
1048}
1049
1050void MetalCodeGenerator::writeConstructorCompoundVector(const ConstructorCompound& c,
1051 Precedence parentPrecedence) {
1052 SkASSERT(c.type().isVector());
1053
1054 // Metal supports constructing vectors from a mix of scalars and vectors, but not matrices.
1055 // GLSL supports vec4(mat2x2), so we detect that case here and emit a helper function.
1056 if (c.type().columns() == 4 && c.argumentSpan().size() == 1) {
1057 const Expression& expr = *c.argumentSpan().front();
1058 if (expr.type().isMatrix()) {
1059 SkASSERT(expr.type().rows() == 2);
1060 SkASSERT(expr.type().columns() == 2);
1061 this->writeVectorFromMat2x2ConstructorHelper();
1062 this->write("float4_from_float2x2(");
1063 this->writeExpression(expr, Precedence::kSequence);
1064 this->write(")");
1065 return;
1066 }
1067 }
1068
1069 this->writeAnyConstructor(c, "(", ")", parentPrecedence);
1070}
1071
John Stiles8cad6372021-04-07 12:31:13 -04001072void MetalCodeGenerator::writeConstructorCompoundMatrix(const ConstructorCompound& c,
1073 Precedence parentPrecedence) {
John Stiles6de2e1d2021-07-09 12:41:55 -04001074 SkASSERT(c.type().isMatrix());
1075
John Stiles1bdafbf2020-05-28 12:17:20 -04001076 // Emit and invoke a matrix-constructor helper method if one is necessary.
1077 if (this->matrixConstructHelperIsNeeded(c)) {
1078 this->write(this->getMatrixConstructHelper(c));
John Stiles1fa15b12020-05-28 17:36:54 +00001079 this->write("(");
1080 const char* separator = "";
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001081 for (const std::unique_ptr<Expression>& expr : c.arguments()) {
John Stiles1fa15b12020-05-28 17:36:54 +00001082 this->write(separator);
1083 separator = ", ";
Brian Osman00185012021-02-04 16:07:11 -05001084 this->writeExpression(*expr, Precedence::kSequence);
John Stilesdaa573e2020-05-28 12:17:20 -04001085 }
John Stiles1fa15b12020-05-28 17:36:54 +00001086 this->write(")");
John Stiles1bdafbf2020-05-28 12:17:20 -04001087 return;
John Stilesdaa573e2020-05-28 12:17:20 -04001088 }
John Stiles1bdafbf2020-05-28 12:17:20 -04001089
John Stiles2bec8ab2021-04-06 18:40:04 -04001090 // Metal doesn't allow creating matrices by passing in scalars and vectors in a jumble; it
1091 // requires your scalars to be grouped up into columns. Because `matrixConstructHelperIsNeeded`
1092 // returned false, we know that none of our scalars/vectors "wrap" across across a column, so we
1093 // can group our inputs up and synthesize a constructor for each column.
1094 const Type& matrixType = c.type();
1095 const Type& columnType = matrixType.componentType().toCompound(
1096 fContext, /*columns=*/matrixType.rows(), /*rows=*/1);
1097
1098 this->writeType(matrixType);
John Stiles7384b372021-04-01 13:48:15 -04001099 this->write("(");
John Stiles1bdafbf2020-05-28 12:17:20 -04001100 const char* separator = "";
1101 int scalarCount = 0;
Ethan Nicholasf70f0442020-09-29 12:41:35 -04001102 for (const std::unique_ptr<Expression>& arg : c.arguments()) {
John Stiles1bdafbf2020-05-28 12:17:20 -04001103 this->write(separator);
1104 separator = ", ";
John Stiles2bec8ab2021-04-06 18:40:04 -04001105 if (arg->type().columns() < matrixType.rows()) {
1106 // Write a `floatN(` constructor to group scalars and smaller vectors together.
John Stiles1bdafbf2020-05-28 12:17:20 -04001107 if (!scalarCount) {
John Stiles2bec8ab2021-04-06 18:40:04 -04001108 this->writeType(columnType);
John Stiles1bdafbf2020-05-28 12:17:20 -04001109 this->write("(");
1110 }
John Stiles2bec8ab2021-04-06 18:40:04 -04001111 scalarCount += arg->type().columns();
John Stiles1bdafbf2020-05-28 12:17:20 -04001112 }
Brian Osman00185012021-02-04 16:07:11 -05001113 this->writeExpression(*arg, Precedence::kSequence);
John Stiles2bec8ab2021-04-06 18:40:04 -04001114 if (scalarCount && scalarCount == matrixType.rows()) {
1115 // Close our `floatN(...` constructor block from above.
John Stiles1bdafbf2020-05-28 12:17:20 -04001116 this->write(")");
1117 scalarCount = 0;
1118 }
1119 }
John Stiles7384b372021-04-01 13:48:15 -04001120 this->write(")");
Ethan Nicholascc305772017-10-13 16:17:45 -04001121}
1122
John Stilesb14a8192021-04-05 11:40:46 -04001123void MetalCodeGenerator::writeAnyConstructor(const AnyConstructor& c,
1124 const char* leftBracket,
1125 const char* rightBracket,
1126 Precedence parentPrecedence) {
John Stilese1182782021-03-30 22:09:37 -04001127 this->writeType(c.type());
John Stilesb14a8192021-04-05 11:40:46 -04001128 this->write(leftBracket);
John Stiles7384b372021-04-01 13:48:15 -04001129 const char* separator = "";
John Stilesb14a8192021-04-05 11:40:46 -04001130 for (const std::unique_ptr<Expression>& arg : c.argumentSpan()) {
John Stiles7384b372021-04-01 13:48:15 -04001131 this->write(separator);
1132 separator = ", ";
1133 this->writeExpression(*arg, Precedence::kSequence);
1134 }
John Stilesb14a8192021-04-05 11:40:46 -04001135 this->write(rightBracket);
John Stiles7384b372021-04-01 13:48:15 -04001136}
1137
John Stilesb14a8192021-04-05 11:40:46 -04001138void MetalCodeGenerator::writeCastConstructor(const AnyConstructor& c,
1139 const char* leftBracket,
1140 const char* rightBracket,
1141 Precedence parentPrecedence) {
1142 // If the type is coercible, emit it directly without the cast.
1143 auto args = c.argumentSpan();
1144 if (args.size() == 1) {
1145 if (this->canCoerce(c.type(), args.front()->type())) {
1146 this->writeExpression(*args.front(), parentPrecedence);
1147 return;
1148 }
John Stilesfd7252f2021-04-04 22:24:40 -04001149 }
1150
John Stilesb14a8192021-04-05 11:40:46 -04001151 return this->writeAnyConstructor(c, leftBracket, rightBracket, parentPrecedence);
John Stilesfd7252f2021-04-04 22:24:40 -04001152}
1153
Ethan Nicholascc305772017-10-13 16:17:45 -04001154void MetalCodeGenerator::writeFragCoord() {
Brian Salomond8d85b92021-07-07 09:41:17 -04001155 SkASSERT(fRTFlipName.length());
1156 this->write("float4(_fragCoord.x, ");
1157 this->write(fRTFlipName.c_str());
1158 this->write(".x + ");
1159 this->write(fRTFlipName.c_str());
1160 this->write(".y * _fragCoord.y, 0.0, _fragCoord.w)");
Ethan Nicholascc305772017-10-13 16:17:45 -04001161}
1162
1163void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
John Stiles06b84ef2020-12-09 12:35:48 -05001164 // When assembling out-param helper functions, we copy variables into local clones with matching
John Stilesf7410bd2021-01-19 13:07:55 -05001165 // names. We never want to prepend "_in." or "_globals." when writing these variables since
John Stiles06b84ef2020-12-09 12:35:48 -05001166 // we're actually targeting the clones.
1167 if (fIgnoreVariableReferenceModifiers) {
1168 this->writeName(ref.variable()->name());
1169 return;
1170 }
1171
Ethan Nicholas78686922020-10-08 06:46:27 -04001172 switch (ref.variable()->modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001173 case SK_FRAGCOLOR_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001174 this->write("_out.sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -04001175 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -04001176 case SK_FRAGCOORD_BUILTIN:
1177 this->writeFragCoord();
1178 break;
Timothy Liangdc89f192018-06-13 09:20:31 -04001179 case SK_VERTEXID_BUILTIN:
1180 this->write("sk_VertexID");
1181 break;
1182 case SK_INSTANCEID_BUILTIN:
1183 this->write("sk_InstanceID");
1184 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -04001185 case SK_CLOCKWISE_BUILTIN:
1186 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
Brian Salomonf4ba4ec2020-03-19 15:54:28 -04001187 // clockwise to match Skia convention.
Brian Salomond8d85b92021-07-07 09:41:17 -04001188 this->write("(" + fRTFlipName + ".y < 0 ? _frontFacing : !_frontFacing)");
Timothy Liang7b8875d2018-08-10 09:42:31 -04001189 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001190 default:
Ethan Nicholas78686922020-10-08 06:46:27 -04001191 const Variable& var = *ref.variable();
Ethan Nicholas453f67f2020-10-09 10:43:45 -04001192 if (var.storage() == Variable::Storage::kGlobal) {
Ethan Nicholas78686922020-10-08 06:46:27 -04001193 if (var.modifiers().fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001194 this->write("_in.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001195 } else if (var.modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf7410bd2021-01-19 13:07:55 -05001196 this->write("_out.");
Ethan Nicholas78686922020-10-08 06:46:27 -04001197 } else if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
1198 var.type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001199 this->write("_uniforms.");
1200 } else {
John Stilesf7410bd2021-01-19 13:07:55 -05001201 this->write("_globals.");
Ethan Nicholascc305772017-10-13 16:17:45 -04001202 }
1203 }
Ethan Nicholas78686922020-10-08 06:46:27 -04001204 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001205 }
1206}
1207
1208void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
Brian Osman00185012021-02-04 16:07:11 -05001209 this->writeExpression(*expr.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001210 this->write("[");
Brian Osman00185012021-02-04 16:07:11 -05001211 this->writeExpression(*expr.index(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001212 this->write("]");
1213}
1214
1215void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001216 const Type::Field* field = &f.base()->type().fields()[f.fieldIndex()];
1217 if (FieldAccess::OwnerKind::kDefault == f.ownerKind()) {
Brian Osman00185012021-02-04 16:07:11 -05001218 this->writeExpression(*f.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001219 this->write(".");
1220 }
Timothy Liang7d637782018-06-05 09:58:07 -04001221 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001222 case SK_POSITION_BUILTIN:
John Stilesf7410bd2021-01-19 13:07:55 -05001223 this->write("_out.sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -04001224 break;
1225 default:
Timothy Liang7d637782018-06-05 09:58:07 -04001226 if (field->fName == "sk_PointSize") {
John Stilesf7410bd2021-01-19 13:07:55 -05001227 this->write("_out.sk_PointSize");
Timothy Liang7d637782018-06-05 09:58:07 -04001228 } else {
Ethan Nicholas7a95b202020-10-09 11:55:40 -04001229 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
John Stilesf7410bd2021-01-19 13:07:55 -05001230 this->write("_globals.");
Timothy Liang7d637782018-06-05 09:58:07 -04001231 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
1232 this->write("->");
1233 }
Timothy Liang651286f2018-06-07 09:55:33 -04001234 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001235 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001236 }
1237}
1238
1239void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Brian Osman00185012021-02-04 16:07:11 -05001240 this->writeExpression(*swizzle.base(), Precedence::kPostfix);
Ethan Nicholascc305772017-10-13 16:17:45 -04001241 this->write(".");
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04001242 for (int c : swizzle.components()) {
Brian Osman25647672020-09-15 15:16:56 -04001243 SkASSERT(c >= 0 && c <= 3);
1244 this->write(&("x\0y\0z\0w\0"[c * 2]));
Ethan Nicholascc305772017-10-13 16:17:45 -04001245 }
1246}
1247
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001248void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
1249 const Type& result) {
John Stilesc985e142021-05-13 14:01:48 -04001250 SkASSERT(left.isMatrix());
1251 SkASSERT(right.isMatrix());
1252 SkASSERT(result.isMatrix());
1253 SkASSERT(left.rows() == right.rows());
1254 SkASSERT(left.columns() == right.columns());
1255 SkASSERT(left.rows() == result.rows());
1256 SkASSERT(left.columns() == result.columns());
1257
1258 String key = "Matrix *= " + this->typeName(left) + ":" + this->typeName(right);
John Stiles56233d12021-02-03 13:03:29 -05001259
1260 auto [iter, wasInserted] = fHelpers.insert(key);
1261 if (wasInserted) {
John Stiles368db7c2020-12-29 11:20:08 -05001262 fExtraFunctions.printf("thread %s& operator*=(thread %s& left, thread const %s& right) {\n"
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001263 " left = left * right;\n"
1264 " return left;\n"
John Stiles368db7c2020-12-29 11:20:08 -05001265 "}\n",
1266 this->typeName(result).c_str(), this->typeName(left).c_str(),
1267 this->typeName(right).c_str());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001268 }
1269}
1270
John Stiles39346472021-04-29 14:39:35 -04001271void MetalCodeGenerator::writeMatrixEqualityHelpers(const Type& left, const Type& right) {
1272 SkASSERT(left.isMatrix());
1273 SkASSERT(right.isMatrix());
1274 SkASSERT(left.rows() == right.rows());
1275 SkASSERT(left.columns() == right.columns());
John Stiles01cdf012021-02-10 09:53:41 -05001276
John Stilesc985e142021-05-13 14:01:48 -04001277 String key = "Matrix == " + this->typeName(left) + ":" + this->typeName(right);
John Stiles01cdf012021-02-10 09:53:41 -05001278
1279 auto [iter, wasInserted] = fHelpers.insert(key);
1280 if (wasInserted) {
1281 fExtraFunctions.printf(
1282 "thread bool operator==(const %s left, const %s right) {\n"
John Stiles39346472021-04-29 14:39:35 -04001283 " return ",
John Stiles01cdf012021-02-10 09:53:41 -05001284 this->typeName(left).c_str(), this->typeName(right).c_str());
1285
John Stiles39346472021-04-29 14:39:35 -04001286 const char* separator = "";
John Stiles01cdf012021-02-10 09:53:41 -05001287 for (int index=0; index<left.columns(); ++index) {
John Stiles39346472021-04-29 14:39:35 -04001288 fExtraFunctions.printf("%sall(left[%d] == right[%d])", separator, index, index);
1289 separator = " &&\n ";
John Stiles01cdf012021-02-10 09:53:41 -05001290 }
John Stiles39346472021-04-29 14:39:35 -04001291
1292 fExtraFunctions.printf(
1293 ";\n"
1294 "}\n"
1295 "thread bool operator!=(const %s left, const %s right) {\n"
1296 " return !(left == right);\n"
1297 "}\n",
1298 this->typeName(left).c_str(), this->typeName(right).c_str());
John Stiles01cdf012021-02-10 09:53:41 -05001299 }
1300}
1301
John Stilesc985e142021-05-13 14:01:48 -04001302void MetalCodeGenerator::writeMatrixDivisionHelpers(const Type& type) {
1303 SkASSERT(type.isMatrix());
1304
1305 String key = "Matrix / " + this->typeName(type);
1306
1307 auto [iter, wasInserted] = fHelpers.insert(key);
1308 if (wasInserted) {
1309 String typeName = this->typeName(type);
1310
1311 fExtraFunctions.printf(
1312 "thread %s operator/(const %s left, const %s right) {\n"
1313 " return %s(",
1314 typeName.c_str(), typeName.c_str(), typeName.c_str(), typeName.c_str());
1315
1316 const char* separator = "";
1317 for (int index=0; index<type.columns(); ++index) {
1318 fExtraFunctions.printf("%sleft[%d] / right[%d]", separator, index, index);
1319 separator = ", ";
1320 }
1321
1322 fExtraFunctions.printf(");\n"
1323 "}\n"
1324 "thread %s& operator/=(thread %s& left, thread const %s& right) {\n"
1325 " left = left / right;\n"
1326 " return left;\n"
1327 "}\n",
1328 typeName.c_str(), typeName.c_str(), typeName.c_str());
1329 }
1330}
1331
John Stiles39346472021-04-29 14:39:35 -04001332void MetalCodeGenerator::writeArrayEqualityHelpers(const Type& type) {
1333 SkASSERT(type.isArray());
John Stiles01cdf012021-02-10 09:53:41 -05001334
John Stiles39346472021-04-29 14:39:35 -04001335 // If the array's component type needs a helper as well, we need to emit that one first.
1336 this->writeEqualityHelpers(type.componentType(), type.componentType());
1337
1338 auto [iter, wasInserted] = fHelpers.insert("ArrayEquality []");
1339 if (wasInserted) {
1340 fExtraFunctions.writeText(R"(
1341template <typename T, size_t N>
1342bool operator==(thread const array<T, N>& left, thread const array<T, N>& right) {
1343 for (size_t index = 0; index < N; ++index) {
1344 if (!(left[index] == right[index])) {
1345 return false;
1346 }
1347 }
1348 return true;
1349}
1350
1351template <typename T, size_t N>
1352bool operator!=(thread const array<T, N>& left, thread const array<T, N>& right) {
1353 return !(left == right);
1354}
1355)");
1356 }
1357}
1358
1359void MetalCodeGenerator::writeStructEqualityHelpers(const Type& type) {
1360 SkASSERT(type.isStruct());
1361 String key = "StructEquality " + this->typeName(type);
John Stiles01cdf012021-02-10 09:53:41 -05001362
1363 auto [iter, wasInserted] = fHelpers.insert(key);
1364 if (wasInserted) {
John Stiles39346472021-04-29 14:39:35 -04001365 // If one of the struct's fields needs a helper as well, we need to emit that one first.
1366 for (const Type::Field& field : type.fields()) {
1367 this->writeEqualityHelpers(*field.fType, *field.fType);
John Stiles830c69c2021-04-28 17:16:16 -04001368 }
John Stiles39346472021-04-29 14:39:35 -04001369
1370 // Write operator== and operator!= for this struct, since those are assumed to exist in SkSL
1371 // and GLSL but do not exist by default in Metal.
1372 fExtraFunctions.printf(
1373 "thread bool operator==(thread const %s& left, thread const %s& right) {\n"
1374 " return ",
1375 this->typeName(type).c_str(),
1376 this->typeName(type).c_str());
1377
1378 const char* separator = "";
1379 for (const Type::Field& field : type.fields()) {
1380 fExtraFunctions.printf("%s(left.%.*s == right.%.*s)",
1381 separator,
1382 (int)field.fName.size(), field.fName.data(),
1383 (int)field.fName.size(), field.fName.data());
1384 separator = " &&\n ";
1385 }
1386 fExtraFunctions.printf(
1387 ";\n"
1388 "}\n"
1389 "thread bool operator!=(thread const %s& left, thread const %s& right) {\n"
1390 " return !(left == right);\n"
1391 "}\n",
1392 this->typeName(type).c_str(),
1393 this->typeName(type).c_str());
1394 }
1395}
1396
1397void MetalCodeGenerator::writeEqualityHelpers(const Type& leftType, const Type& rightType) {
1398 if (leftType.isArray() && rightType.isArray()) {
1399 this->writeArrayEqualityHelpers(leftType);
1400 return;
1401 }
1402 if (leftType.isStruct() && rightType.isStruct()) {
1403 this->writeStructEqualityHelpers(leftType);
1404 return;
1405 }
1406 if (leftType.isMatrix() && rightType.isMatrix()) {
1407 this->writeMatrixEqualityHelpers(leftType, rightType);
1408 return;
John Stiles01cdf012021-02-10 09:53:41 -05001409 }
1410}
1411
John Stiles6b131292021-05-12 17:12:21 -04001412void MetalCodeGenerator::writeNumberAsMatrix(const Expression& expr, const Type& matrixType) {
1413 SkASSERT(expr.type().isNumber());
1414 SkASSERT(matrixType.isMatrix());
1415
1416 // Componentwise multiply the scalar against a matrix of the desired size which contains all 1s.
1417 this->write("(");
1418 this->writeType(matrixType);
1419 this->write("(");
1420
1421 const char* separator = "";
1422 for (int index = matrixType.slotCount(); index--;) {
1423 this->write(separator);
1424 this->write("1.0");
1425 separator = ", ";
1426 }
1427
1428 this->write(") * ");
1429 this->writeExpression(expr, Precedence::kMultiplicative);
1430 this->write(")");
1431}
1432
Ethan Nicholascc305772017-10-13 16:17:45 -04001433void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
1434 Precedence parentPrecedence) {
John Stiles2d4f9592020-10-30 10:29:12 -04001435 const Expression& left = *b.left();
1436 const Expression& right = *b.right();
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001437 const Type& leftType = left.type();
1438 const Type& rightType = right.type();
John Stiles45990502021-02-16 10:55:27 -05001439 Operator op = b.getOperator();
1440 Precedence precedence = op.getBinaryPrecedence();
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001441 bool needParens = precedence >= parentPrecedence;
John Stiles45990502021-02-16 10:55:27 -05001442 switch (op.kind()) {
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001443 case Token::Kind::TK_EQEQ:
John Stiles39346472021-04-29 14:39:35 -04001444 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001445 if (leftType.isVector()) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001446 this->write("all");
1447 needParens = true;
1448 }
1449 break;
Ethan Nicholas5a9e7fb2020-04-17 12:45:51 -04001450 case Token::Kind::TK_NEQ:
John Stiles39346472021-04-29 14:39:35 -04001451 this->writeEqualityHelpers(leftType, rightType);
John Stiles9aeed132020-11-24 17:36:06 -05001452 if (leftType.isVector()) {
Jim Van Verth36477b42019-04-11 14:57:30 -04001453 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001454 needParens = true;
1455 }
1456 break;
1457 default:
1458 break;
1459 }
John Stiles39346472021-04-29 14:39:35 -04001460 if (leftType.isMatrix() && rightType.isMatrix() && op.kind() == Token::Kind::TK_STAREQ) {
1461 this->writeMatrixTimesEqualHelper(leftType, rightType, b.type());
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001462 }
John Stilesc985e142021-05-13 14:01:48 -04001463 if (op.removeAssignment().kind() == Token::Kind::TK_SLASH &&
1464 ((leftType.isMatrix() && rightType.isMatrix()) ||
1465 (leftType.isScalar() && rightType.isMatrix()) ||
1466 (leftType.isMatrix() && rightType.isScalar()))) {
1467 this->writeMatrixDivisionHelpers(leftType.isMatrix() ? leftType : rightType);
1468 }
1469 if (needParens) {
1470 this->write("(");
1471 }
John Stiles6011bbc2021-05-19 22:56:18 -04001472 bool needMatrixSplatOnScalar = rightType.isMatrix() && leftType.isNumber() &&
1473 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001474 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1475 if (needMatrixSplatOnScalar) {
1476 this->writeNumberAsMatrix(left, rightType);
1477 } else {
1478 this->writeExpression(left, precedence);
1479 }
John Stiles45990502021-02-16 10:55:27 -05001480 if (op.kind() != Token::Kind::TK_EQ && op.isAssignment() &&
Ethan Nicholasc8d9c8e2020-09-22 15:05:37 -04001481 left.kind() == Expression::Kind::kSwizzle && !left.hasSideEffects()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001482 // This doesn't compile in Metal:
1483 // float4 x = float4(1);
1484 // x.xy *= float2x2(...);
1485 // with the error message "non-const reference cannot bind to vector element",
1486 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
1487 // as long as the LHS has no side effects, and hope for the best otherwise.
1488 this->write(" = ");
Brian Osman00185012021-02-04 16:07:11 -05001489 this->writeExpression(left, Precedence::kAssignment);
Ethan Nicholascc305772017-10-13 16:17:45 -04001490 this->write(" ");
John Stiles7cbe66b2021-05-12 17:01:23 -04001491 this->write(OperatorName(op.removeAssignment()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001492 this->write(" ");
1493 } else {
John Stilesd6449e92020-11-30 09:13:23 -05001494 this->write(String(" ") + OperatorName(op) + " ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001495 }
John Stiles6b131292021-05-12 17:12:21 -04001496
John Stiles6011bbc2021-05-19 22:56:18 -04001497 needMatrixSplatOnScalar = leftType.isMatrix() && rightType.isNumber() &&
1498 op.isValidForMatrixOrVector() &&
John Stiles6b131292021-05-12 17:12:21 -04001499 op.removeAssignment().kind() != Token::Kind::TK_STAR;
1500 if (needMatrixSplatOnScalar) {
1501 this->writeNumberAsMatrix(right, leftType);
1502 } else {
1503 this->writeExpression(right, precedence);
1504 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -05001505 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001506 this->write(")");
1507 }
1508}
1509
1510void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
1511 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001512 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001513 this->write("(");
1514 }
Brian Osman00185012021-02-04 16:07:11 -05001515 this->writeExpression(*t.test(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001516 this->write(" ? ");
Brian Osman00185012021-02-04 16:07:11 -05001517 this->writeExpression(*t.ifTrue(), Precedence::kTernary);
Ethan Nicholascc305772017-10-13 16:17:45 -04001518 this->write(" : ");
Brian Osman00185012021-02-04 16:07:11 -05001519 this->writeExpression(*t.ifFalse(), Precedence::kTernary);
1520 if (Precedence::kTernary >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001521 this->write(")");
1522 }
1523}
1524
1525void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
1526 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001527 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001528 this->write("(");
1529 }
John Stilesd6449e92020-11-30 09:13:23 -05001530 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001531 this->writeExpression(*p.operand(), Precedence::kPrefix);
1532 if (Precedence::kPrefix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001533 this->write(")");
1534 }
1535}
1536
1537void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
1538 Precedence parentPrecedence) {
Brian Osman00185012021-02-04 16:07:11 -05001539 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001540 this->write("(");
1541 }
Brian Osman00185012021-02-04 16:07:11 -05001542 this->writeExpression(*p.operand(), Precedence::kPostfix);
John Stilesd6449e92020-11-30 09:13:23 -05001543 this->write(OperatorName(p.getOperator()));
Brian Osman00185012021-02-04 16:07:11 -05001544 if (Precedence::kPostfix >= parentPrecedence) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001545 this->write(")");
1546 }
1547}
1548
1549void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
Ethan Nicholas59d660c2020-09-28 09:18:15 -04001550 this->write(b.value() ? "true" : "false");
Ethan Nicholascc305772017-10-13 16:17:45 -04001551}
1552
1553void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
John Stiles12739df2020-12-29 09:47:20 -05001554 const Type& type = i.type();
John Stiles54e7c052021-01-11 14:22:36 -05001555 if (type == *fContext.fTypes.fUInt) {
Ethan Nicholase96cdd12020-09-28 16:27:18 -04001556 this->write(to_string(i.value() & 0xffffffff) + "u");
John Stiles54e7c052021-01-11 14:22:36 -05001557 } else if (type == *fContext.fTypes.fUShort) {
John Stiles12739df2020-12-29 09:47:20 -05001558 this->write(to_string(i.value() & 0xffff) + "u");
Ethan Nicholascc305772017-10-13 16:17:45 -04001559 } else {
John Stiles12739df2020-12-29 09:47:20 -05001560 this->write(to_string(i.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001561 }
1562}
1563
1564void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
Ethan Nicholasa3f22f12020-10-01 12:13:17 -04001565 this->write(to_string(f.value()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001566}
1567
1568void MetalCodeGenerator::writeSetting(const Setting& s) {
John Stilesf57207b2021-02-02 17:50:34 -05001569 SK_ABORT("internal error; setting was not folded to a constant during compilation\n");
Ethan Nicholascc305772017-10-13 16:17:45 -04001570}
1571
John Stiles06b84ef2020-12-09 12:35:48 -05001572void MetalCodeGenerator::writeFunctionRequirementArgs(const FunctionDeclaration& f,
1573 const char*& separator) {
1574 Requirements requirements = this->requirements(f);
1575 if (requirements & kInputs_Requirement) {
1576 this->write(separator);
1577 this->write("_in");
1578 separator = ", ";
1579 }
1580 if (requirements & kOutputs_Requirement) {
1581 this->write(separator);
1582 this->write("_out");
1583 separator = ", ";
1584 }
1585 if (requirements & kUniforms_Requirement) {
1586 this->write(separator);
1587 this->write("_uniforms");
1588 separator = ", ";
1589 }
1590 if (requirements & kGlobals_Requirement) {
1591 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001592 this->write("_globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001593 separator = ", ";
1594 }
1595 if (requirements & kFragCoord_Requirement) {
1596 this->write(separator);
1597 this->write("_fragCoord");
1598 separator = ", ";
1599 }
1600}
1601
1602void MetalCodeGenerator::writeFunctionRequirementParams(const FunctionDeclaration& f,
1603 const char*& separator) {
1604 Requirements requirements = this->requirements(f);
1605 if (requirements & kInputs_Requirement) {
1606 this->write(separator);
1607 this->write("Inputs _in");
1608 separator = ", ";
1609 }
1610 if (requirements & kOutputs_Requirement) {
1611 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001612 this->write("thread Outputs& _out");
John Stiles06b84ef2020-12-09 12:35:48 -05001613 separator = ", ";
1614 }
1615 if (requirements & kUniforms_Requirement) {
1616 this->write(separator);
1617 this->write("Uniforms _uniforms");
1618 separator = ", ";
1619 }
1620 if (requirements & kGlobals_Requirement) {
1621 this->write(separator);
John Stilesf7410bd2021-01-19 13:07:55 -05001622 this->write("thread Globals& _globals");
John Stiles06b84ef2020-12-09 12:35:48 -05001623 separator = ", ";
1624 }
1625 if (requirements & kFragCoord_Requirement) {
1626 this->write(separator);
1627 this->write("float4 _fragCoord");
1628 separator = ", ";
1629 }
1630}
1631
John Stilesda5cdf62021-01-28 11:47:29 -05001632int MetalCodeGenerator::getUniformBinding(const Modifiers& m) {
1633 return (m.fLayout.fBinding >= 0) ? m.fLayout.fBinding
John Stiles270cec22021-02-17 12:59:36 -05001634 : fProgram.fConfig->fSettings.fDefaultUniformBinding;
John Stilesda5cdf62021-01-28 11:47:29 -05001635}
1636
1637int MetalCodeGenerator::getUniformSet(const Modifiers& m) {
1638 return (m.fLayout.fSet >= 0) ? m.fLayout.fSet
John Stiles270cec22021-02-17 12:59:36 -05001639 : fProgram.fConfig->fSettings.fDefaultUniformSet;
John Stilesda5cdf62021-01-28 11:47:29 -05001640}
1641
John Stiles569249b2020-11-03 12:18:22 -05001642bool MetalCodeGenerator::writeFunctionDeclaration(const FunctionDeclaration& f) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001643 fRTFlipName = fProgram.fInputs.fUseFlipRTUniform
1644 ? "_globals._anonInterface0->" SKSL_RTFLIP_NAME
1645 : "";
Ethan Nicholascc305772017-10-13 16:17:45 -04001646 const char* separator = "";
John Stilese8da4d22021-03-24 09:19:45 -04001647 if (f.isMain()) {
John Stiles270cec22021-02-17 12:59:36 -05001648 switch (fProgram.fConfig->fKind) {
John Stilesdbd4e6f2021-02-16 13:29:15 -05001649 case ProgramKind::kFragment:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001650 this->write("fragment Outputs fragmentMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001651 break;
John Stilesdbd4e6f2021-02-16 13:29:15 -05001652 case ProgramKind::kVertex:
Timothy Liangb8eeb802018-07-23 16:46:16 -04001653 this->write("vertex Outputs vertexMain");
Ethan Nicholascc305772017-10-13 16:17:45 -04001654 break;
1655 default:
John Stiles3fabfc02020-09-25 15:51:28 -04001656 fErrors.error(-1, "unsupported kind of program");
John Stiles569249b2020-11-03 12:18:22 -05001657 return false;
Ethan Nicholascc305772017-10-13 16:17:45 -04001658 }
1659 this->write("(Inputs _in [[stage_in]]");
1660 if (-1 != fUniformBuffer) {
1661 this->write(", constant Uniforms& _uniforms [[buffer(" +
1662 to_string(fUniformBuffer) + ")]]");
1663 }
Brian Osman133724c2020-10-28 14:14:39 -04001664 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04001665 if (e->is<GlobalVarDeclaration>()) {
1666 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001667 const VarDeclaration& var = decls.declaration()->as<VarDeclaration>();
1668 if (var.var().type().typeKind() == Type::TypeKind::kSampler) {
1669 if (var.var().modifiers().fLayout.fBinding < 0) {
Brian Osmanc0213602020-10-06 14:43:32 -04001670 fErrors.error(decls.fOffset,
John Stilesb41d5bb2021-01-26 16:28:12 -05001671 "Metal samplers must have 'layout(binding=...)'");
John Stiles569249b2020-11-03 12:18:22 -05001672 return false;
Timothy Liangee84fe12018-05-18 14:38:19 -04001673 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001674 if (var.var().type().dimensions() != SpvDim2D) {
John Stiles569249b2020-11-03 12:18:22 -05001675 // Not yet implemented--Skia currently only uses 2D textures.
Brian Osmanc0213602020-10-06 14:43:32 -04001676 fErrors.error(decls.fOffset, "Unsupported texture dimensions");
John Stiles569249b2020-11-03 12:18:22 -05001677 return false;
Brian Osmanc0213602020-10-06 14:43:32 -04001678 }
1679 this->write(", texture2d<float> ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001680 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001681 this->write("[[texture(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001682 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001683 this->write(")]]");
1684 this->write(", sampler ");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001685 this->writeName(var.var().name());
Brian Osmanc0213602020-10-06 14:43:32 -04001686 this->write(SAMPLER_SUFFIX);
1687 this->write("[[sampler(");
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04001688 this->write(to_string(var.var().modifiers().fLayout.fBinding));
Brian Osmanc0213602020-10-06 14:43:32 -04001689 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001690 }
Brian Osman1179fcf2020-10-08 16:04:40 -04001691 } else if (e->is<InterfaceBlock>()) {
1692 const InterfaceBlock& intf = e->as<InterfaceBlock>();
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001693 if (intf.typeName() == "sk_PerVertex") {
Timothy Lianga06f2152018-05-24 15:33:31 -04001694 continue;
1695 }
1696 this->write(", constant ");
John Stilesb4418502021-02-04 10:57:08 -05001697 this->writeType(intf.variable().type());
Timothy Lianga06f2152018-05-24 15:33:31 -04001698 this->write("& " );
1699 this->write(fInterfaceBlockNameMap[&intf]);
1700 this->write(" [[buffer(");
John Stilesda5cdf62021-01-28 11:47:29 -05001701 this->write(to_string(this->getUniformBinding(intf.variable().modifiers())));
Timothy Lianga06f2152018-05-24 15:33:31 -04001702 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -04001703 }
1704 }
John Stiles270cec22021-02-17 12:59:36 -05001705 if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Salomond8d85b92021-07-07 09:41:17 -04001706 if (fProgram.fInputs.fUseFlipRTUniform && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -04001707 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
Brian Salomond8d85b92021-07-07 09:41:17 -04001708 fRTFlipName = "_anonInterface0." SKSL_RTFLIP_NAME;
Timothy Liang5422f9a2018-08-10 10:57:55 -04001709 }
Timothy Liang7b8875d2018-08-10 09:42:31 -04001710 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001711 this->write(", float4 _fragCoord [[position]]");
John Stiles270cec22021-02-17 12:59:36 -05001712 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001713 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001714 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001715 separator = ", ";
1716 } else {
John Stilesb4418502021-02-04 10:57:08 -05001717 this->writeType(f.returnType());
Timothy Liang651286f2018-06-07 09:55:33 -04001718 this->write(" ");
John Stilese1068342021-03-22 11:57:41 -04001719 this->writeName(f.mangledName());
Timothy Liang651286f2018-06-07 09:55:33 -04001720 this->write("(");
John Stiles06b84ef2020-12-09 12:35:48 -05001721 this->writeFunctionRequirementParams(f, separator);
Ethan Nicholascc305772017-10-13 16:17:45 -04001722 }
John Stiles569249b2020-11-03 12:18:22 -05001723 for (const auto& param : f.parameters()) {
Brian Osman716aeb92021-04-21 13:20:00 -04001724 if (f.isMain() && param->modifiers().fLayout.fBuiltin != -1) {
1725 continue;
1726 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001727 this->write(separator);
1728 separator = ", ";
Brian Osman58134e12021-05-13 14:51:07 -04001729 this->writeModifiers(param->modifiers());
Ethan Nicholas30d30222020-09-11 12:27:26 -04001730 const Type* type = &param->type();
John Stilesb4418502021-02-04 10:57:08 -05001731 this->writeType(*type);
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04001732 if (param->modifiers().fFlags & Modifiers::kOut_Flag) {
John Stilesf2bd5012020-12-04 11:58:26 -05001733 this->write("&");
Ethan Nicholascc305772017-10-13 16:17:45 -04001734 }
Timothy Liang651286f2018-06-07 09:55:33 -04001735 this->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04001736 this->writeName(param->name());
Ethan Nicholascc305772017-10-13 16:17:45 -04001737 }
John Stiles569249b2020-11-03 12:18:22 -05001738 this->write(")");
1739 return true;
1740}
Ethan Nicholascc305772017-10-13 16:17:45 -04001741
John Stiles569249b2020-11-03 12:18:22 -05001742void MetalCodeGenerator::writeFunctionPrototype(const FunctionPrototype& f) {
1743 this->writeFunctionDeclaration(f.declaration());
1744 this->writeLine(";");
1745}
1746
John Stiles986c7fb2020-12-01 14:44:56 -05001747static bool is_block_ending_with_return(const Statement* stmt) {
1748 // This function detects (potentially nested) blocks that end in a return statement.
1749 if (!stmt->is<Block>()) {
1750 return false;
1751 }
1752 const StatementArray& block = stmt->as<Block>().children();
1753 for (int index = block.count(); index--; ) {
John Stiles628777c2021-08-04 22:07:41 -04001754 stmt = block[index].get();
1755 if (stmt->is<ReturnStatement>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001756 return true;
1757 }
John Stiles628777c2021-08-04 22:07:41 -04001758 if (stmt->is<Block>()) {
1759 return is_block_ending_with_return(stmt);
John Stiles986c7fb2020-12-01 14:44:56 -05001760 }
John Stiles628777c2021-08-04 22:07:41 -04001761 if (!stmt->is<Nop>()) {
John Stiles986c7fb2020-12-01 14:44:56 -05001762 break;
1763 }
1764 }
1765 return false;
1766}
1767
John Stiles569249b2020-11-03 12:18:22 -05001768void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
John Stiles270cec22021-02-17 12:59:36 -05001769 SkASSERT(!fProgram.fConfig->fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -04001770
John Stiles569249b2020-11-03 12:18:22 -05001771 if (!this->writeFunctionDeclaration(f.declaration())) {
1772 return;
1773 }
1774
John Stiles986c7fb2020-12-01 14:44:56 -05001775 fCurrentFunction = &f.declaration();
1776 SkScopeExit clearCurrentFunction([&] { fCurrentFunction = nullptr; });
1777
John Stiles569249b2020-11-03 12:18:22 -05001778 this->writeLine(" {");
1779
John Stilese8da4d22021-03-24 09:19:45 -04001780 if (f.declaration().isMain()) {
John Stilescdcdb042020-07-06 09:03:51 -04001781 this->writeGlobalInit();
John Stilesf7410bd2021-01-19 13:07:55 -05001782 this->writeLine(" Outputs _out;");
John Stiles37279172021-01-21 22:24:28 -05001783 this->writeLine(" (void)_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001784 }
John Stilesc67b3622020-05-28 17:53:13 -04001785
John Stiles95680232021-04-22 15:05:20 -04001786 fFunctionHeader.clear();
Ethan Nicholascc305772017-10-13 16:17:45 -04001787 StringStream buffer;
John Stiles44532372020-12-07 12:33:55 -05001788 {
1789 AutoOutputStream outputToBuffer(this, &buffer);
1790 fIndentation++;
1791 for (const std::unique_ptr<Statement>& stmt : f.body()->as<Block>().children()) {
1792 if (!stmt->isEmpty()) {
1793 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001794 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001795 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001796 }
John Stilese8da4d22021-03-24 09:19:45 -04001797 if (f.declaration().isMain()) {
John Stiles44532372020-12-07 12:33:55 -05001798 // If the main function doesn't end with a return, we need to synthesize one here.
1799 if (!is_block_ending_with_return(f.body().get())) {
1800 this->writeReturnStatementFromMain();
John Stilese8b5a732021-03-12 13:25:52 -05001801 this->finishLine();
John Stiles44532372020-12-07 12:33:55 -05001802 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001803 }
John Stiles44532372020-12-07 12:33:55 -05001804 fIndentation--;
1805 this->writeLine("}");
Ethan Nicholascc305772017-10-13 16:17:45 -04001806 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001807 this->write(fFunctionHeader);
1808 this->write(buffer.str());
1809}
1810
Brian Osman58134e12021-05-13 14:51:07 -04001811void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001812 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1813 this->write("thread ");
1814 }
1815 if (modifiers.fFlags & Modifiers::kConst_Flag) {
John Stiles0bd55782021-02-09 18:29:40 -05001816 this->write("const ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001817 }
1818}
1819
1820void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001821 if ("sk_PerVertex" == intf.typeName()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001822 return;
1823 }
Brian Osman58134e12021-05-13 14:51:07 -04001824 this->writeModifiers(intf.variable().modifiers());
Timothy Liangdc89f192018-06-13 09:20:31 -04001825 this->write("struct ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001826 this->writeLine(intf.typeName() + " {");
1827 const Type* structType = &intf.variable().type();
John Stilesbb43b7e2020-12-03 17:36:32 -05001828 if (structType->isArray()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001829 structType = &structType->componentType();
1830 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001831 fIndentation++;
John Stiles3dba3ee2020-12-02 23:35:49 -05001832 this->writeFields(structType->fields(), structType->fOffset, &intf);
Brian Salomond8d85b92021-07-07 09:41:17 -04001833 if (fProgram.fInputs.fUseFlipRTUniform) {
1834 this->writeLine("float2 " SKSL_RTFLIP_NAME ";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001835 }
1836 fIndentation--;
1837 this->write("}");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001838 if (intf.instanceName().size()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001839 this->write(" ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001840 this->write(intf.instanceName());
John Stilesd39aec02020-12-03 10:42:26 -05001841 if (intf.arraySize() > 0) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001842 this->write("[");
John Stilesd39aec02020-12-03 10:42:26 -05001843 this->write(to_string(intf.arraySize()));
Ethan Nicholascc305772017-10-13 16:17:45 -04001844 this->write("]");
John Stilesd39aec02020-12-03 10:42:26 -05001845 } else if (intf.arraySize() == Type::kUnsizedArray){
1846 this->write("[]");
Ethan Nicholascc305772017-10-13 16:17:45 -04001847 }
Ethan Nicholaseaf47882020-10-15 10:10:08 -04001848 fInterfaceBlockNameMap[&intf] = intf.instanceName();
Timothy Lianga06f2152018-05-24 15:33:31 -04001849 } else {
Ethan Nicholas3533ff12021-08-02 12:53:29 -04001850 fInterfaceBlockNameMap[&intf] = *fProgram.fSymbols->takeOwnershipOfString("_anonInterface" +
1851 to_string(fAnonInterfaceCount++));
Ethan Nicholascc305772017-10-13 16:17:45 -04001852 }
1853 this->writeLine(";");
1854}
1855
Timothy Liangdc89f192018-06-13 09:20:31 -04001856void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1857 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001858 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
Timothy Liangdc89f192018-06-13 09:20:31 -04001859 int currentOffset = 0;
John Stiles39346472021-04-29 14:39:35 -04001860 for (const Type::Field& field : fields) {
Timothy Liangdc89f192018-06-13 09:20:31 -04001861 int fieldOffset = field.fModifiers.fLayout.fOffset;
1862 const Type* fieldType = field.fType;
John Stiles21f5f452020-11-30 09:57:59 -05001863 if (!MemoryLayout::LayoutIsSupported(*fieldType)) {
John Stiles0023c0c2020-11-16 13:32:18 -05001864 fErrors.error(parentOffset, "type '" + fieldType->name() + "' is not permitted here");
1865 return;
1866 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001867 if (fieldOffset != -1) {
1868 if (currentOffset > fieldOffset) {
1869 fErrors.error(parentOffset,
John Stilesd7199b22020-12-30 16:22:58 -05001870 "offset of field '" + field.fName + "' must be at least " +
1871 to_string((int) currentOffset));
Brian Osman8609a242020-09-08 14:01:49 -04001872 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001873 } else if (currentOffset < fieldOffset) {
1874 this->write("char pad");
1875 this->write(to_string(fPaddingCount++));
1876 this->write("[");
1877 this->write(to_string(fieldOffset - currentOffset));
1878 this->writeLine("];");
1879 currentOffset = fieldOffset;
1880 }
1881 int alignment = memoryLayout.alignment(*fieldType);
1882 if (fieldOffset % alignment) {
1883 fErrors.error(parentOffset,
1884 "offset of field '" + field.fName + "' must be a multiple of " +
1885 to_string((int) alignment));
Brian Osman8609a242020-09-08 14:01:49 -04001886 return;
Timothy Liangdc89f192018-06-13 09:20:31 -04001887 }
1888 }
Brian Osman8609a242020-09-08 14:01:49 -04001889 size_t fieldSize = memoryLayout.size(*fieldType);
1890 if (fieldSize > static_cast<size_t>(std::numeric_limits<int>::max() - currentOffset)) {
1891 fErrors.error(parentOffset, "field offset overflow");
1892 return;
1893 }
1894 currentOffset += fieldSize;
Brian Osman58134e12021-05-13 14:51:07 -04001895 this->writeModifiers(field.fModifiers);
John Stilesb4418502021-02-04 10:57:08 -05001896 this->writeType(*fieldType);
Timothy Liangdc89f192018-06-13 09:20:31 -04001897 this->write(" ");
1898 this->writeName(field.fName);
Timothy Liangdc89f192018-06-13 09:20:31 -04001899 this->writeLine(";");
1900 if (parentIntf) {
1901 fInterfaceBlockMap[&field] = parentIntf;
1902 }
1903 }
1904}
1905
Ethan Nicholascc305772017-10-13 16:17:45 -04001906void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
Brian Osman00185012021-02-04 16:07:11 -05001907 this->writeExpression(value, Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001908}
1909
Ethan Nicholas962dec42021-06-10 13:06:39 -04001910void MetalCodeGenerator::writeName(skstd::string_view name) {
Timothy Liang651286f2018-06-07 09:55:33 -04001911 if (fReservedWords.find(name) != fReservedWords.end()) {
1912 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1913 }
1914 this->write(name);
1915}
1916
Brian Osman58134e12021-05-13 14:51:07 -04001917void MetalCodeGenerator::writeVarDeclaration(const VarDeclaration& varDecl) {
1918 this->writeModifiers(varDecl.var().modifiers());
John Stilesb4418502021-02-04 10:57:08 -05001919 this->writeType(varDecl.var().type());
Brian Osmanc0213602020-10-06 14:43:32 -04001920 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05001921 this->writeName(varDecl.var().name());
1922 if (varDecl.value()) {
Brian Osmanc0213602020-10-06 14:43:32 -04001923 this->write(" = ");
John Stilesb4418502021-02-04 10:57:08 -05001924 this->writeVarInitializer(varDecl.var(), *varDecl.value());
Brian Osmanc0213602020-10-06 14:43:32 -04001925 }
1926 this->write(";");
Ethan Nicholascc305772017-10-13 16:17:45 -04001927}
1928
1929void MetalCodeGenerator::writeStatement(const Statement& s) {
Ethan Nicholase6592142020-09-08 10:22:09 -04001930 switch (s.kind()) {
1931 case Statement::Kind::kBlock:
John Stiles26f98502020-08-18 09:30:51 -04001932 this->writeBlock(s.as<Block>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001933 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001934 case Statement::Kind::kExpression:
Brian Osman00185012021-02-04 16:07:11 -05001935 this->writeExpression(*s.as<ExpressionStatement>().expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001936 this->write(";");
1937 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001938 case Statement::Kind::kReturn:
John Stiles26f98502020-08-18 09:30:51 -04001939 this->writeReturnStatement(s.as<ReturnStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001940 break;
Brian Osmanc0213602020-10-06 14:43:32 -04001941 case Statement::Kind::kVarDeclaration:
Brian Osman58134e12021-05-13 14:51:07 -04001942 this->writeVarDeclaration(s.as<VarDeclaration>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001943 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001944 case Statement::Kind::kIf:
John Stiles26f98502020-08-18 09:30:51 -04001945 this->writeIfStatement(s.as<IfStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001946 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001947 case Statement::Kind::kFor:
John Stiles26f98502020-08-18 09:30:51 -04001948 this->writeForStatement(s.as<ForStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001949 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001950 case Statement::Kind::kDo:
John Stiles26f98502020-08-18 09:30:51 -04001951 this->writeDoStatement(s.as<DoStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001952 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001953 case Statement::Kind::kSwitch:
John Stiles26f98502020-08-18 09:30:51 -04001954 this->writeSwitchStatement(s.as<SwitchStatement>());
Ethan Nicholascc305772017-10-13 16:17:45 -04001955 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001956 case Statement::Kind::kBreak:
Ethan Nicholascc305772017-10-13 16:17:45 -04001957 this->write("break;");
1958 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001959 case Statement::Kind::kContinue:
Ethan Nicholascc305772017-10-13 16:17:45 -04001960 this->write("continue;");
1961 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04001962 case Statement::Kind::kDiscard:
Timothy Lianga06f2152018-05-24 15:33:31 -04001963 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001964 break;
John Stiles98c1f822020-09-09 14:18:53 -04001965 case Statement::Kind::kInlineMarker:
Ethan Nicholase6592142020-09-08 10:22:09 -04001966 case Statement::Kind::kNop:
Ethan Nicholascc305772017-10-13 16:17:45 -04001967 this->write(";");
1968 break;
1969 default:
John Stileseada7bc2021-02-02 16:29:32 -05001970 SkDEBUGFAILF("unsupported statement: %s", s.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05001971 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04001972 }
1973}
1974
Ethan Nicholascc305772017-10-13 16:17:45 -04001975void MetalCodeGenerator::writeBlock(const Block& b) {
John Stiles3744bd62021-01-26 13:49:43 -05001976 // Write scope markers if this block is a scope, or if the block is empty (since we need to emit
1977 // something here to make the code valid).
1978 bool isScope = b.isScope() || b.isEmpty();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001979 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001980 this->writeLine("{");
1981 fIndentation++;
1982 }
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001983 for (const std::unique_ptr<Statement>& stmt : b.children()) {
1984 if (!stmt->isEmpty()) {
1985 this->writeStatement(*stmt);
John Stilese8b5a732021-03-12 13:25:52 -05001986 this->finishLine();
Ethan Nicholas7bd60432020-09-25 14:31:59 -04001987 }
1988 }
1989 if (isScope) {
Ethan Nicholas70728ef2020-05-28 07:09:00 -04001990 fIndentation--;
1991 this->write("}");
1992 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001993}
1994
1995void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1996 this->write("if (");
Brian Osman00185012021-02-04 16:07:11 -05001997 this->writeExpression(*stmt.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04001998 this->write(") ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04001999 this->writeStatement(*stmt.ifTrue());
2000 if (stmt.ifFalse()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002001 this->write(" else ");
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002002 this->writeStatement(*stmt.ifFalse());
Ethan Nicholascc305772017-10-13 16:17:45 -04002003 }
2004}
2005
2006void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
Brian Osmand6f23382020-12-15 17:08:59 -05002007 // Emit loops of the form 'for(;test;)' as 'while(test)', which is probably how they started
2008 if (!f.initializer() && f.test() && !f.next()) {
2009 this->write("while (");
Brian Osman00185012021-02-04 16:07:11 -05002010 this->writeExpression(*f.test(), Precedence::kTopLevel);
Brian Osmand6f23382020-12-15 17:08:59 -05002011 this->write(") ");
2012 this->writeStatement(*f.statement());
2013 return;
2014 }
2015
John Stiles1a15e572021-04-19 14:57:15 -04002016 this->write("for (");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002017 if (f.initializer() && !f.initializer()->isEmpty()) {
John Stiles1a15e572021-04-19 14:57:15 -04002018 this->writeStatement(*f.initializer());
Ethan Nicholascc305772017-10-13 16:17:45 -04002019 } else {
John Stiles1a15e572021-04-19 14:57:15 -04002020 this->write("; ");
Ethan Nicholascc305772017-10-13 16:17:45 -04002021 }
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002022 if (f.test()) {
Brian Osman00185012021-02-04 16:07:11 -05002023 this->writeExpression(*f.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002024 }
2025 this->write("; ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002026 if (f.next()) {
Brian Osman00185012021-02-04 16:07:11 -05002027 this->writeExpression(*f.next(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002028 }
2029 this->write(") ");
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002030 this->writeStatement(*f.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002031}
2032
Ethan Nicholascc305772017-10-13 16:17:45 -04002033void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
2034 this->write("do ");
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002035 this->writeStatement(*d.statement());
Ethan Nicholascc305772017-10-13 16:17:45 -04002036 this->write(" while (");
Brian Osman00185012021-02-04 16:07:11 -05002037 this->writeExpression(*d.test(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002038 this->write(");");
2039}
2040
2041void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
2042 this->write("switch (");
Brian Osman00185012021-02-04 16:07:11 -05002043 this->writeExpression(*s.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002044 this->writeLine(") {");
2045 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002046 for (const std::unique_ptr<Statement>& stmt : s.cases()) {
2047 const SwitchCase& c = stmt->as<SwitchCase>();
2048 if (c.value()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002049 this->write("case ");
John Stilesb23a64b2021-03-11 08:27:59 -05002050 this->writeExpression(*c.value(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002051 this->writeLine(":");
2052 } else {
2053 this->writeLine("default:");
2054 }
John Stilesb23a64b2021-03-11 08:27:59 -05002055 if (!c.statement()->isEmpty()) {
John Stilesc3ce43b2021-03-09 15:37:01 -05002056 fIndentation++;
John Stilesb23a64b2021-03-11 08:27:59 -05002057 this->writeStatement(*c.statement());
John Stilese8b5a732021-03-12 13:25:52 -05002058 this->finishLine();
John Stilesc3ce43b2021-03-09 15:37:01 -05002059 fIndentation--;
Ethan Nicholascc305772017-10-13 16:17:45 -04002060 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002061 }
2062 fIndentation--;
2063 this->write("}");
2064}
2065
John Stiles986c7fb2020-12-01 14:44:56 -05002066void MetalCodeGenerator::writeReturnStatementFromMain() {
2067 // main functions in Metal return a magic _out parameter that doesn't exist in SkSL.
John Stiles270cec22021-02-17 12:59:36 -05002068 switch (fProgram.fConfig->fKind) {
Brian Salomon3e2fe2b2021-06-02 09:16:30 -04002069 case ProgramKind::kVertex:
John Stilesdbd4e6f2021-02-16 13:29:15 -05002070 case ProgramKind::kFragment:
John Stilesf7410bd2021-01-19 13:07:55 -05002071 this->write("return _out;");
John Stiles986c7fb2020-12-01 14:44:56 -05002072 break;
John Stiles986c7fb2020-12-01 14:44:56 -05002073 default:
2074 SkDEBUGFAIL("unsupported kind of program");
2075 }
2076}
2077
Ethan Nicholascc305772017-10-13 16:17:45 -04002078void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
John Stilese8da4d22021-03-24 09:19:45 -04002079 if (fCurrentFunction && fCurrentFunction->isMain()) {
John Stiles986c7fb2020-12-01 14:44:56 -05002080 if (r.expression()) {
John Stiles97d18172021-01-22 16:47:42 -05002081 if (r.expression()->type() == *fContext.fTypes.fHalf4) {
2082 this->write("_out.sk_FragColor = ");
Brian Osman00185012021-02-04 16:07:11 -05002083 this->writeExpression(*r.expression(), Precedence::kTopLevel);
John Stiles97d18172021-01-22 16:47:42 -05002084 this->writeLine(";");
2085 } else {
2086 fErrors.error(r.fOffset, "Metal does not support returning '" +
2087 r.expression()->type().description() + "' from main()");
2088 }
John Stiles986c7fb2020-12-01 14:44:56 -05002089 }
2090 this->writeReturnStatementFromMain();
2091 return;
2092 }
2093
Ethan Nicholascc305772017-10-13 16:17:45 -04002094 this->write("return");
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002095 if (r.expression()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002096 this->write(" ");
Brian Osman00185012021-02-04 16:07:11 -05002097 this->writeExpression(*r.expression(), Precedence::kTopLevel);
Ethan Nicholascc305772017-10-13 16:17:45 -04002098 }
2099 this->write(";");
2100}
2101
Michael Ludwigbf58add2021-03-16 10:40:11 -04002102void MetalCodeGenerator::writeHeader() {
2103 this->write("#include <metal_stdlib>\n");
2104 this->write("#include <simd/simd.h>\n");
2105 this->write("using namespace metal;\n");
2106}
2107
Ethan Nicholascc305772017-10-13 16:17:45 -04002108void MetalCodeGenerator::writeUniformStruct() {
Brian Osman133724c2020-10-28 14:14:39 -04002109 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002110 if (e->is<GlobalVarDeclaration>()) {
2111 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002112 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002113 if (var.modifiers().fFlags & Modifiers::kUniform_Flag &&
Brian Osmanc0213602020-10-06 14:43:32 -04002114 var.type().typeKind() != Type::TypeKind::kSampler) {
John Stilesda5cdf62021-01-28 11:47:29 -05002115 int uniformSet = this->getUniformSet(var.modifiers());
John Stilesd8fc95d2021-01-26 16:22:53 -05002116 // Make sure that the program's uniform-set value is consistent throughout.
Ethan Nicholascc305772017-10-13 16:17:45 -04002117 if (-1 == fUniformBuffer) {
2118 this->write("struct Uniforms {\n");
John Stilesd8fc95d2021-01-26 16:22:53 -05002119 fUniformBuffer = uniformSet;
2120 } else if (uniformSet != fUniformBuffer) {
2121 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
2122 "the same 'layout(set=...)'");
Ethan Nicholascc305772017-10-13 16:17:45 -04002123 }
2124 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002125 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002126 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002127 this->writeName(var.name());
Ethan Nicholascc305772017-10-13 16:17:45 -04002128 this->write(";\n");
2129 }
2130 }
2131 }
2132 if (-1 != fUniformBuffer) {
2133 this->write("};\n");
2134 }
2135}
2136
2137void MetalCodeGenerator::writeInputStruct() {
2138 this->write("struct Inputs {\n");
Brian Osman133724c2020-10-28 14:14:39 -04002139 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002140 if (e->is<GlobalVarDeclaration>()) {
2141 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002142 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002143 if (var.modifiers().fFlags & Modifiers::kIn_Flag &&
2144 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002145 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002146 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002147 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002148 this->writeName(var.name());
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002149 if (-1 != var.modifiers().fLayout.fLocation) {
John Stiles270cec22021-02-17 12:59:36 -05002150 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Brian Osmanc0213602020-10-06 14:43:32 -04002151 this->write(" [[attribute(" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002152 to_string(var.modifiers().fLayout.fLocation) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002153 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Brian Osmanc0213602020-10-06 14:43:32 -04002154 this->write(" [[user(locn" +
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002155 to_string(var.modifiers().fLayout.fLocation) + ")]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002156 }
2157 }
2158 this->write(";\n");
2159 }
2160 }
2161 }
2162 this->write("};\n");
2163}
2164
2165void MetalCodeGenerator::writeOutputStruct() {
2166 this->write("struct Outputs {\n");
John Stiles270cec22021-02-17 12:59:36 -05002167 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04002168 this->write(" float4 sk_Position [[position]];\n");
John Stiles270cec22021-02-17 12:59:36 -05002169 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
Timothy Liangde0be802018-08-10 13:48:08 -04002170 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002171 }
Brian Osman133724c2020-10-28 14:14:39 -04002172 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002173 if (e->is<GlobalVarDeclaration>()) {
2174 const GlobalVarDeclaration& decls = e->as<GlobalVarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002175 const Variable& var = decls.declaration()->as<VarDeclaration>().var();
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002176 if (var.modifiers().fFlags & Modifiers::kOut_Flag &&
2177 -1 == var.modifiers().fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002178 this->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002179 this->writeType(var.type());
Ethan Nicholascc305772017-10-13 16:17:45 -04002180 this->write(" ");
Brian Osmanc0213602020-10-06 14:43:32 -04002181 this->writeName(var.name());
John Stiles842b3592020-12-01 10:36:37 -05002182
2183 int location = var.modifiers().fLayout.fLocation;
2184 if (location < 0) {
2185 fErrors.error(var.fOffset,
2186 "Metal out variables must have 'layout(location=...)'");
John Stiles270cec22021-02-17 12:59:36 -05002187 } else if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
John Stiles842b3592020-12-01 10:36:37 -05002188 this->write(" [[user(locn" + to_string(location) + ")]]");
John Stiles270cec22021-02-17 12:59:36 -05002189 } else if (fProgram.fConfig->fKind == ProgramKind::kFragment) {
John Stiles842b3592020-12-01 10:36:37 -05002190 this->write(" [[color(" + to_string(location) + ")");
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002191 int colorIndex = var.modifiers().fLayout.fIndex;
Brian Osmanc0213602020-10-06 14:43:32 -04002192 if (colorIndex) {
2193 this->write(", index(" + to_string(colorIndex) + ")");
Timothy Liang7d637782018-06-05 09:58:07 -04002194 }
Brian Osmanc0213602020-10-06 14:43:32 -04002195 this->write("]]");
Ethan Nicholascc305772017-10-13 16:17:45 -04002196 }
2197 this->write(";\n");
2198 }
2199 }
Timothy Liang7d637782018-06-05 09:58:07 -04002200 }
John Stiles270cec22021-02-17 12:59:36 -05002201 if (fProgram.fConfig->fKind == ProgramKind::kVertex) {
Jim Van Verth3913d3e2020-08-31 15:16:57 -04002202 this->write(" float sk_PointSize [[point_size]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04002203 }
2204 this->write("};\n");
2205}
2206
2207void MetalCodeGenerator::writeInterfaceBlocks() {
2208 bool wroteInterfaceBlock = false;
Brian Osman133724c2020-10-28 14:14:39 -04002209 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002210 if (e->is<InterfaceBlock>()) {
2211 this->writeInterfaceBlock(e->as<InterfaceBlock>());
Timothy Liang7d637782018-06-05 09:58:07 -04002212 wroteInterfaceBlock = true;
2213 }
2214 }
Brian Salomond8d85b92021-07-07 09:41:17 -04002215 if (!wroteInterfaceBlock && fProgram.fInputs.fUseFlipRTUniform) {
Timothy Liang7d637782018-06-05 09:58:07 -04002216 this->writeLine("struct sksl_synthetic_uniforms {");
Brian Salomond8d85b92021-07-07 09:41:17 -04002217 this->writeLine(" float2 " SKSL_RTFLIP_NAME ";");
Timothy Liang7d637782018-06-05 09:58:07 -04002218 this->writeLine("};");
2219 }
Ethan Nicholascc305772017-10-13 16:17:45 -04002220}
2221
John Stilesdc75a972020-11-25 16:24:55 -05002222void MetalCodeGenerator::writeStructDefinitions() {
2223 for (const ProgramElement* e : fProgram.elements()) {
2224 if (e->is<StructDefinition>()) {
Brian Osman02bc5222021-01-28 11:00:20 -05002225 this->writeStructDefinition(e->as<StructDefinition>());
John Stilesdc75a972020-11-25 16:24:55 -05002226 }
2227 }
2228}
2229
John Stilescdcdb042020-07-06 09:03:51 -04002230void MetalCodeGenerator::visitGlobalStruct(GlobalStructVisitor* visitor) {
2231 // Visit the interface blocks.
2232 for (const auto& [interfaceType, interfaceName] : fInterfaceBlockNameMap) {
John Stilesfdb8dbe2020-12-04 11:00:03 -05002233 visitor->visitInterfaceBlock(*interfaceType, interfaceName);
John Stilescdcdb042020-07-06 09:03:51 -04002234 }
Brian Osman133724c2020-10-28 14:14:39 -04002235 for (const ProgramElement* element : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002236 if (!element->is<GlobalVarDeclaration>()) {
John Stilescdcdb042020-07-06 09:03:51 -04002237 continue;
Timothy Liang7d637782018-06-05 09:58:07 -04002238 }
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002239 const GlobalVarDeclaration& global = element->as<GlobalVarDeclaration>();
2240 const VarDeclaration& decl = global.declaration()->as<VarDeclaration>();
2241 const Variable& var = decl.var();
Brian Osman58134e12021-05-13 14:51:07 -04002242 if (var.type().typeKind() == Type::TypeKind::kSampler) {
2243 // Samplers are represented as a "texture/sampler" duo in the global struct.
2244 visitor->visitTexture(var.type(), var.name());
Ethan Nicholasd2e09602021-06-10 11:21:59 -04002245 visitor->visitSampler(var.type(), var.name() + SAMPLER_SUFFIX);
Brian Osman58134e12021-05-13 14:51:07 -04002246 continue;
2247 }
2248
2249 if (!(var.modifiers().fFlags & ~Modifiers::kConst_Flag) &&
2250 -1 == var.modifiers().fLayout.fBuiltin) {
2251 // Visit a regular variable.
2252 visitor->visitVariable(var, decl.value().get());
Timothy Liangee84fe12018-05-18 14:38:19 -04002253 }
2254 }
John Stilescdcdb042020-07-06 09:03:51 -04002255}
2256
2257void MetalCodeGenerator::writeGlobalStruct() {
2258 class : public GlobalStructVisitor {
2259 public:
Ethan Nicholas962dec42021-06-10 13:06:39 -04002260 void visitInterfaceBlock(const InterfaceBlock& block,
2261 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002262 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002263 fCodeGen->write(" constant ");
Ethan Nicholaseaf47882020-10-15 10:10:08 -04002264 fCodeGen->write(block.typeName());
John Stilescdcdb042020-07-06 09:03:51 -04002265 fCodeGen->write("* ");
2266 fCodeGen->writeName(blockName);
2267 fCodeGen->write(";\n");
2268 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002269 void visitTexture(const Type& type, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002270 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002271 fCodeGen->write(" ");
John Stilesb4418502021-02-04 10:57:08 -05002272 fCodeGen->writeType(type);
John Stilescdcdb042020-07-06 09:03:51 -04002273 fCodeGen->write(" ");
2274 fCodeGen->writeName(name);
2275 fCodeGen->write(";\n");
2276 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002277 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002278 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002279 fCodeGen->write(" sampler ");
2280 fCodeGen->writeName(name);
2281 fCodeGen->write(";\n");
2282 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002283 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002284 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002285 fCodeGen->write(" ");
Brian Osman58134e12021-05-13 14:51:07 -04002286 fCodeGen->writeModifiers(var.modifiers());
John Stilesb4418502021-02-04 10:57:08 -05002287 fCodeGen->writeType(var.type());
John Stilescdcdb042020-07-06 09:03:51 -04002288 fCodeGen->write(" ");
Ethan Nicholase2c49992020-10-05 11:49:11 -04002289 fCodeGen->writeName(var.name());
John Stilescdcdb042020-07-06 09:03:51 -04002290 fCodeGen->write(";\n");
2291 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002292 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002293 if (fFirst) {
2294 fCodeGen->write("struct Globals {\n");
2295 fFirst = false;
2296 }
2297 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002298 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002299 if (!fFirst) {
John Stiles83f3b8d2020-12-07 17:52:25 -05002300 fCodeGen->writeLine("};");
John Stilescdcdb042020-07-06 09:03:51 -04002301 fFirst = true;
2302 }
2303 }
2304
2305 MetalCodeGenerator* fCodeGen = nullptr;
2306 bool fFirst = true;
2307 } visitor;
2308
2309 visitor.fCodeGen = this;
2310 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002311 visitor.finish();
John Stilescdcdb042020-07-06 09:03:51 -04002312}
2313
2314void MetalCodeGenerator::writeGlobalInit() {
2315 class : public GlobalStructVisitor {
2316 public:
John Stilesfdb8dbe2020-12-04 11:00:03 -05002317 void visitInterfaceBlock(const InterfaceBlock& blockType,
Ethan Nicholas962dec42021-06-10 13:06:39 -04002318 skstd::string_view blockName) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002319 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002320 fCodeGen->write("&");
2321 fCodeGen->writeName(blockName);
2322 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002323 void visitTexture(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002324 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002325 fCodeGen->writeName(name);
2326 }
Ethan Nicholas962dec42021-06-10 13:06:39 -04002327 void visitSampler(const Type&, skstd::string_view name) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002328 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002329 fCodeGen->writeName(name);
2330 }
John Stilesfdb8dbe2020-12-04 11:00:03 -05002331 void visitVariable(const Variable& var, const Expression* value) override {
John Stiles83f3b8d2020-12-07 17:52:25 -05002332 this->addElement();
John Stilescdcdb042020-07-06 09:03:51 -04002333 if (value) {
2334 fCodeGen->writeVarInitializer(var, *value);
2335 } else {
2336 fCodeGen->write("{}");
2337 }
2338 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002339 void addElement() {
John Stilescdcdb042020-07-06 09:03:51 -04002340 if (fFirst) {
John Stilesf7410bd2021-01-19 13:07:55 -05002341 fCodeGen->write(" Globals _globals{");
John Stilescdcdb042020-07-06 09:03:51 -04002342 fFirst = false;
2343 } else {
2344 fCodeGen->write(", ");
2345 }
2346 }
John Stiles83f3b8d2020-12-07 17:52:25 -05002347 void finish() {
John Stilescdcdb042020-07-06 09:03:51 -04002348 if (!fFirst) {
2349 fCodeGen->writeLine("};");
John Stiles37279172021-01-21 22:24:28 -05002350 fCodeGen->writeLine(" (void)_globals;");
John Stilescdcdb042020-07-06 09:03:51 -04002351 }
2352 }
2353 MetalCodeGenerator* fCodeGen = nullptr;
2354 bool fFirst = true;
2355 } visitor;
2356
2357 visitor.fCodeGen = this;
2358 this->visitGlobalStruct(&visitor);
John Stiles83f3b8d2020-12-07 17:52:25 -05002359 visitor.finish();
Timothy Liangee84fe12018-05-18 14:38:19 -04002360}
2361
Ethan Nicholascc305772017-10-13 16:17:45 -04002362void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
Ethan Nicholase6592142020-09-08 10:22:09 -04002363 switch (e.kind()) {
2364 case ProgramElement::Kind::kExtension:
Ethan Nicholascc305772017-10-13 16:17:45 -04002365 break;
Brian Osman58134e12021-05-13 14:51:07 -04002366 case ProgramElement::Kind::kGlobalVar:
Ethan Nicholascc305772017-10-13 16:17:45 -04002367 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002368 case ProgramElement::Kind::kInterfaceBlock:
Timothy Liang7d637782018-06-05 09:58:07 -04002369 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04002370 break;
John Stilesdc75a972020-11-25 16:24:55 -05002371 case ProgramElement::Kind::kStructDefinition:
2372 // Handled in writeStructDefinitions. Do nothing.
2373 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002374 case ProgramElement::Kind::kFunction:
John Stiles3dc0da62020-08-19 17:48:31 -04002375 this->writeFunction(e.as<FunctionDefinition>());
Ethan Nicholascc305772017-10-13 16:17:45 -04002376 break;
John Stiles569249b2020-11-03 12:18:22 -05002377 case ProgramElement::Kind::kFunctionPrototype:
2378 this->writeFunctionPrototype(e.as<FunctionPrototype>());
2379 break;
Ethan Nicholase6592142020-09-08 10:22:09 -04002380 case ProgramElement::Kind::kModifiers:
Brian Osman58134e12021-05-13 14:51:07 -04002381 this->writeModifiers(e.as<ModifiersDeclaration>().modifiers());
Ethan Nicholascc305772017-10-13 16:17:45 -04002382 this->writeLine(";");
2383 break;
2384 default:
John Stileseada7bc2021-02-02 16:29:32 -05002385 SkDEBUGFAILF("unsupported program element: %s\n", e.description().c_str());
Ethan Nicholas2a099da2020-01-02 14:40:54 -05002386 break;
Ethan Nicholascc305772017-10-13 16:17:45 -04002387 }
2388}
2389
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002390MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression* e) {
2391 if (!e) {
2392 return kNo_Requirements;
2393 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002394 switch (e->kind()) {
2395 case Expression::Kind::kFunctionCall: {
John Stiles3dc0da62020-08-19 17:48:31 -04002396 const FunctionCall& f = e->as<FunctionCall>();
Ethan Nicholas0dec9922020-10-05 15:51:52 -04002397 Requirements result = this->requirements(f.function());
2398 for (const auto& arg : f.arguments()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002399 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002400 }
2401 return result;
2402 }
John Stiles8cad6372021-04-07 12:31:13 -04002403 case Expression::Kind::kConstructorCompound:
2404 case Expression::Kind::kConstructorCompoundCast:
John Stiles7384b372021-04-01 13:48:15 -04002405 case Expression::Kind::kConstructorArray:
John Stiles2938eea2021-04-01 18:58:25 -04002406 case Expression::Kind::kConstructorDiagonalMatrix:
John Stilesfd7252f2021-04-04 22:24:40 -04002407 case Expression::Kind::kConstructorScalarCast:
John Stilesd47330f2021-04-08 23:25:52 -04002408 case Expression::Kind::kConstructorSplat:
2409 case Expression::Kind::kConstructorStruct: {
John Stiles7384b372021-04-01 13:48:15 -04002410 const AnyConstructor& c = e->asAnyConstructor();
Ethan Nicholascc305772017-10-13 16:17:45 -04002411 Requirements result = kNo_Requirements;
John Stilesd8eb8752021-04-01 11:49:10 -04002412 for (const auto& arg : c.argumentSpan()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002413 result |= this->requirements(arg.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002414 }
2415 return result;
2416 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002417 case Expression::Kind::kFieldAccess: {
John Stiles3dc0da62020-08-19 17:48:31 -04002418 const FieldAccess& f = e->as<FieldAccess>();
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002419 if (FieldAccess::OwnerKind::kAnonymousInterfaceBlock == f.ownerKind()) {
Timothy Liang7d637782018-06-05 09:58:07 -04002420 return kGlobals_Requirement;
2421 }
Ethan Nicholas7a95b202020-10-09 11:55:40 -04002422 return this->requirements(f.base().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002423 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002424 case Expression::Kind::kSwizzle:
Ethan Nicholas6b4d5812020-10-12 16:11:51 -04002425 return this->requirements(e->as<Swizzle>().base().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002426 case Expression::Kind::kBinary: {
2427 const BinaryExpression& bin = e->as<BinaryExpression>();
John Stiles2d4f9592020-10-30 10:29:12 -04002428 return this->requirements(bin.left().get()) |
2429 this->requirements(bin.right().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002430 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002431 case Expression::Kind::kIndex: {
John Stiles3dc0da62020-08-19 17:48:31 -04002432 const IndexExpression& idx = e->as<IndexExpression>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002433 return this->requirements(idx.base().get()) | this->requirements(idx.index().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002434 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002435 case Expression::Kind::kPrefix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002436 return this->requirements(e->as<PrefixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002437 case Expression::Kind::kPostfix:
Ethan Nicholas444ccc62020-10-09 10:16:22 -04002438 return this->requirements(e->as<PostfixExpression>().operand().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002439 case Expression::Kind::kTernary: {
John Stiles3dc0da62020-08-19 17:48:31 -04002440 const TernaryExpression& t = e->as<TernaryExpression>();
Ethan Nicholasdd218162020-10-08 05:48:01 -04002441 return this->requirements(t.test().get()) | this->requirements(t.ifTrue().get()) |
2442 this->requirements(t.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002443 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002444 case Expression::Kind::kVariableReference: {
John Stiles3dc0da62020-08-19 17:48:31 -04002445 const VariableReference& v = e->as<VariableReference>();
Ethan Nicholas78686922020-10-08 06:46:27 -04002446 const Modifiers& modifiers = v.variable()->modifiers();
Ethan Nicholascc305772017-10-13 16:17:45 -04002447 Requirements result = kNo_Requirements;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002448 if (modifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04002449 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholas453f67f2020-10-09 10:43:45 -04002450 } else if (Variable::Storage::kGlobal == v.variable()->storage()) {
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002451 if (modifiers.fFlags & Modifiers::kIn_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002452 result = kInputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002453 } else if (modifiers.fFlags & Modifiers::kOut_Flag) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002454 result = kOutputs_Requirement;
Ethan Nicholas041fd0a2020-10-07 16:42:04 -04002455 } else if (modifiers.fFlags & Modifiers::kUniform_Flag &&
Ethan Nicholas78686922020-10-08 06:46:27 -04002456 v.variable()->type().typeKind() != Type::TypeKind::kSampler) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002457 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04002458 } else {
2459 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04002460 }
2461 }
2462 return result;
2463 }
2464 default:
2465 return kNo_Requirements;
2466 }
2467}
2468
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002469MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement* s) {
2470 if (!s) {
2471 return kNo_Requirements;
2472 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002473 switch (s->kind()) {
2474 case Statement::Kind::kBlock: {
Ethan Nicholascc305772017-10-13 16:17:45 -04002475 Requirements result = kNo_Requirements;
Ethan Nicholas7bd60432020-09-25 14:31:59 -04002476 for (const std::unique_ptr<Statement>& child : s->as<Block>().children()) {
Ethan Nicholasff350cb2020-05-14 14:05:13 -04002477 result |= this->requirements(child.get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002478 }
2479 return result;
2480 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002481 case Statement::Kind::kVarDeclaration: {
John Stiles3dc0da62020-08-19 17:48:31 -04002482 const VarDeclaration& var = s->as<VarDeclaration>();
Ethan Nicholasc51f33e2020-10-13 13:49:44 -04002483 return this->requirements(var.value().get());
Timothy Liang7d637782018-06-05 09:58:07 -04002484 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002485 case Statement::Kind::kExpression:
Ethan Nicholasd503a5a2020-09-30 09:29:55 -04002486 return this->requirements(s->as<ExpressionStatement>().expression().get());
Ethan Nicholase6592142020-09-08 10:22:09 -04002487 case Statement::Kind::kReturn: {
John Stiles3dc0da62020-08-19 17:48:31 -04002488 const ReturnStatement& r = s->as<ReturnStatement>();
Ethan Nicholas2a4952d2020-10-08 15:35:56 -04002489 return this->requirements(r.expression().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002490 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002491 case Statement::Kind::kIf: {
John Stiles3dc0da62020-08-19 17:48:31 -04002492 const IfStatement& i = s->as<IfStatement>();
Ethan Nicholas8c44eca2020-10-07 16:47:09 -04002493 return this->requirements(i.test().get()) |
2494 this->requirements(i.ifTrue().get()) |
2495 this->requirements(i.ifFalse().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002496 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002497 case Statement::Kind::kFor: {
John Stiles3dc0da62020-08-19 17:48:31 -04002498 const ForStatement& f = s->as<ForStatement>();
Ethan Nicholas0d31ed52020-10-05 14:47:09 -04002499 return this->requirements(f.initializer().get()) |
2500 this->requirements(f.test().get()) |
2501 this->requirements(f.next().get()) |
2502 this->requirements(f.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002503 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002504 case Statement::Kind::kDo: {
John Stiles3dc0da62020-08-19 17:48:31 -04002505 const DoStatement& d = s->as<DoStatement>();
Ethan Nicholas1fd61162020-09-28 13:14:19 -04002506 return this->requirements(d.test().get()) |
2507 this->requirements(d.statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002508 }
Ethan Nicholase6592142020-09-08 10:22:09 -04002509 case Statement::Kind::kSwitch: {
John Stiles3dc0da62020-08-19 17:48:31 -04002510 const SwitchStatement& sw = s->as<SwitchStatement>();
Ethan Nicholas01b05e52020-10-22 15:53:41 -04002511 Requirements result = this->requirements(sw.value().get());
John Stilesb23a64b2021-03-11 08:27:59 -05002512 for (const std::unique_ptr<Statement>& sc : sw.cases()) {
2513 result |= this->requirements(sc->as<SwitchCase>().statement().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002514 }
2515 return result;
2516 }
2517 default:
2518 return kNo_Requirements;
2519 }
2520}
2521
2522MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
Ethan Nicholased84b732020-10-08 11:45:44 -04002523 if (f.isBuiltin()) {
Ethan Nicholascc305772017-10-13 16:17:45 -04002524 return kNo_Requirements;
2525 }
2526 auto found = fRequirements.find(&f);
2527 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04002528 fRequirements[&f] = kNo_Requirements;
Brian Osman133724c2020-10-28 14:14:39 -04002529 for (const ProgramElement* e : fProgram.elements()) {
Brian Osman1179fcf2020-10-08 16:04:40 -04002530 if (e->is<FunctionDefinition>()) {
2531 const FunctionDefinition& def = e->as<FunctionDefinition>();
Ethan Nicholas0a5d0962020-10-14 13:33:18 -04002532 if (&def.declaration() == &f) {
2533 Requirements reqs = this->requirements(def.body().get());
Ethan Nicholascc305772017-10-13 16:17:45 -04002534 fRequirements[&f] = reqs;
2535 return reqs;
2536 }
2537 }
2538 }
John Stiles569249b2020-11-03 12:18:22 -05002539 // We never found a definition for this declared function, but it's legal to prototype a
2540 // function without ever giving a definition, as long as you don't call it.
2541 return kNo_Requirements;
Ethan Nicholascc305772017-10-13 16:17:45 -04002542 }
2543 return found->second;
2544}
2545
Timothy Liangb8eeb802018-07-23 16:46:16 -04002546bool MetalCodeGenerator::generateCode() {
John Stiles44532372020-12-07 12:33:55 -05002547 StringStream header;
2548 {
2549 AutoOutputStream outputToHeader(this, &header, &fIndentation);
Michael Ludwigbf58add2021-03-16 10:40:11 -04002550 this->writeHeader();
John Stiles44532372020-12-07 12:33:55 -05002551 this->writeStructDefinitions();
2552 this->writeUniformStruct();
2553 this->writeInputStruct();
2554 this->writeOutputStruct();
2555 this->writeInterfaceBlocks();
2556 this->writeGlobalStruct();
2557 }
2558 StringStream body;
2559 {
2560 AutoOutputStream outputToBody(this, &body, &fIndentation);
2561 for (const ProgramElement* e : fProgram.elements()) {
2562 this->writeProgramElement(*e);
2563 }
2564 }
2565 write_stringstream(header, *fOut);
2566 write_stringstream(fExtraFunctions, *fOut);
2567 write_stringstream(body, *fOut);
Brian Osman8609a242020-09-08 14:01:49 -04002568 return 0 == fErrors.errorCount();
Ethan Nicholascc305772017-10-13 16:17:45 -04002569}
2570
John Stilesa6841be2020-08-06 14:11:56 -04002571} // namespace SkSL