blob: 916fa9cd0b780ad7cf051848be5f206251f62f4c [file] [log] [blame]
Ethan Nicholascc305772017-10-13 16:17:45 -04001/*
2 * Copyright 2016 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "src/sksl/SkSLMetalCodeGenerator.h"
Ethan Nicholascc305772017-10-13 16:17:45 -04009
Mike Kleinc0bd9f92019-04-23 12:05:21 -050010#include "src/sksl/SkSLCompiler.h"
11#include "src/sksl/ir/SkSLExpressionStatement.h"
12#include "src/sksl/ir/SkSLExtension.h"
13#include "src/sksl/ir/SkSLIndexExpression.h"
14#include "src/sksl/ir/SkSLModifiersDeclaration.h"
15#include "src/sksl/ir/SkSLNop.h"
16#include "src/sksl/ir/SkSLVariableReference.h"
Ethan Nicholascc305772017-10-13 16:17:45 -040017
Timothy Liangb8eeb802018-07-23 16:46:16 -040018#ifdef SK_MOLTENVK
19 static const uint32_t MVKMagicNum = 0x19960412;
20#endif
Timothy Lianga06f2152018-05-24 15:33:31 -040021
Ethan Nicholascc305772017-10-13 16:17:45 -040022namespace SkSL {
23
Timothy Liangee84fe12018-05-18 14:38:19 -040024void MetalCodeGenerator::setupIntrinsics() {
Timothy Liang7d637782018-06-05 09:58:07 -040025#define METAL(x) std::make_pair(kMetal_IntrinsicKind, k ## x ## _MetalIntrinsic)
26#define SPECIAL(x) std::make_pair(kSpecial_IntrinsicKind, k ## x ## _SpecialIntrinsic)
Ethan Nicholas13863662019-07-29 13:05:15 -040027 fIntrinsicMap[String("sample")] = SPECIAL(Texture);
Timothy Liang651286f2018-06-07 09:55:33 -040028 fIntrinsicMap[String("mod")] = SPECIAL(Mod);
Ethan Nicholas0dc80872019-02-08 15:46:24 -050029 fIntrinsicMap[String("equal")] = METAL(Equal);
30 fIntrinsicMap[String("notEqual")] = METAL(NotEqual);
Timothy Lianga06f2152018-05-24 15:33:31 -040031 fIntrinsicMap[String("lessThan")] = METAL(LessThan);
32 fIntrinsicMap[String("lessThanEqual")] = METAL(LessThanEqual);
33 fIntrinsicMap[String("greaterThan")] = METAL(GreaterThan);
34 fIntrinsicMap[String("greaterThanEqual")] = METAL(GreaterThanEqual);
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040035 fIntrinsicMap[String("unpremul")] = SPECIAL(Unpremul);
Timothy Liangee84fe12018-05-18 14:38:19 -040036}
37
Ethan Nicholascc305772017-10-13 16:17:45 -040038void MetalCodeGenerator::write(const char* s) {
39 if (!s[0]) {
40 return;
41 }
42 if (fAtLineStart) {
43 for (int i = 0; i < fIndentation; i++) {
44 fOut->writeText(" ");
45 }
46 }
47 fOut->writeText(s);
48 fAtLineStart = false;
49}
50
51void MetalCodeGenerator::writeLine(const char* s) {
52 this->write(s);
53 fOut->writeText(fLineEnding);
54 fAtLineStart = true;
55}
56
57void MetalCodeGenerator::write(const String& s) {
58 this->write(s.c_str());
59}
60
61void MetalCodeGenerator::writeLine(const String& s) {
62 this->writeLine(s.c_str());
63}
64
65void MetalCodeGenerator::writeLine() {
66 this->writeLine("");
67}
68
69void MetalCodeGenerator::writeExtension(const Extension& ext) {
70 this->writeLine("#extension " + ext.fName + " : enable");
71}
72
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040073String MetalCodeGenerator::getTypeName(const Type& type) {
Ethan Nicholascc305772017-10-13 16:17:45 -040074 switch (type.kind()) {
75 case Type::kStruct_Kind:
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040076 return type.name();
Ethan Nicholascc305772017-10-13 16:17:45 -040077 case Type::kVector_Kind:
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040078 return this->getTypeName(type.componentType()) + to_string(type.columns());
Timothy Liang43d225f2018-07-19 15:27:13 -040079 case Type::kMatrix_Kind:
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040080 return this->getTypeName(type.componentType()) + to_string(type.columns()) + "x" +
81 to_string(type.rows());
Timothy Liangee84fe12018-05-18 14:38:19 -040082 case Type::kSampler_Kind:
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040083 return "texture2d<float>"; // FIXME - support other texture types;
Ethan Nicholascc305772017-10-13 16:17:45 -040084 default:
Timothy Liang43d225f2018-07-19 15:27:13 -040085 if (type == *fContext.fHalf_Type) {
86 // FIXME - Currently only supporting floats in MSL to avoid type coercion issues.
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040087 return fContext.fFloat_Type->name();
Timothy Liang43d225f2018-07-19 15:27:13 -040088 } else if (type == *fContext.fByte_Type) {
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040089 return "char";
Timothy Liang43d225f2018-07-19 15:27:13 -040090 } else if (type == *fContext.fUByte_Type) {
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040091 return "uchar";
Timothy Liang7d637782018-06-05 09:58:07 -040092 } else {
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040093 return type.name();
Timothy Liang7d637782018-06-05 09:58:07 -040094 }
Ethan Nicholascc305772017-10-13 16:17:45 -040095 }
96}
97
Ethan Nicholasffdc3e62019-09-19 16:58:33 -040098void MetalCodeGenerator::writeType(const Type& type) {
99 if (type.kind() == Type::kStruct_Kind) {
100 for (const Type* search : fWrittenStructs) {
101 if (*search == type) {
102 // already written
103 this->write(this->getTypeName(type));
104 return;
105 }
106 }
107 fWrittenStructs.push_back(&type);
108 this->writeLine("struct " + type.name() + " {");
109 fIndentation++;
110 this->writeFields(type.fields(), type.fOffset);
111 fIndentation--;
112 this->write("}");
113 } else {
114 this->write(this->getTypeName(type));
115 }
116}
117
Ethan Nicholascc305772017-10-13 16:17:45 -0400118void MetalCodeGenerator::writeExpression(const Expression& expr, Precedence parentPrecedence) {
119 switch (expr.fKind) {
120 case Expression::kBinary_Kind:
121 this->writeBinaryExpression((BinaryExpression&) expr, parentPrecedence);
122 break;
123 case Expression::kBoolLiteral_Kind:
124 this->writeBoolLiteral((BoolLiteral&) expr);
125 break;
126 case Expression::kConstructor_Kind:
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500127 this->writeConstructor((Constructor&) expr, parentPrecedence);
Ethan Nicholascc305772017-10-13 16:17:45 -0400128 break;
129 case Expression::kIntLiteral_Kind:
130 this->writeIntLiteral((IntLiteral&) expr);
131 break;
132 case Expression::kFieldAccess_Kind:
133 this->writeFieldAccess(((FieldAccess&) expr));
134 break;
135 case Expression::kFloatLiteral_Kind:
136 this->writeFloatLiteral(((FloatLiteral&) expr));
137 break;
138 case Expression::kFunctionCall_Kind:
139 this->writeFunctionCall((FunctionCall&) expr);
140 break;
141 case Expression::kPrefix_Kind:
142 this->writePrefixExpression((PrefixExpression&) expr, parentPrecedence);
143 break;
144 case Expression::kPostfix_Kind:
145 this->writePostfixExpression((PostfixExpression&) expr, parentPrecedence);
146 break;
147 case Expression::kSetting_Kind:
148 this->writeSetting((Setting&) expr);
149 break;
150 case Expression::kSwizzle_Kind:
151 this->writeSwizzle((Swizzle&) expr);
152 break;
153 case Expression::kVariableReference_Kind:
154 this->writeVariableReference((VariableReference&) expr);
155 break;
156 case Expression::kTernary_Kind:
157 this->writeTernaryExpression((TernaryExpression&) expr, parentPrecedence);
158 break;
159 case Expression::kIndex_Kind:
160 this->writeIndexExpression((IndexExpression&) expr);
161 break;
162 default:
163 ABORT("unsupported expression: %s", expr.description().c_str());
164 }
165}
166
Timothy Liang6403b0e2018-05-17 10:40:04 -0400167void MetalCodeGenerator::writeIntrinsicCall(const FunctionCall& c) {
Timothy Liang7d637782018-06-05 09:58:07 -0400168 auto i = fIntrinsicMap.find(c.fFunction.fName);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400169 SkASSERT(i != fIntrinsicMap.end());
Timothy Liang7d637782018-06-05 09:58:07 -0400170 Intrinsic intrinsic = i->second;
171 int32_t intrinsicId = intrinsic.second;
172 switch (intrinsic.first) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400173 case kSpecial_IntrinsicKind:
174 return this->writeSpecialIntrinsic(c, (SpecialIntrinsic) intrinsicId);
Timothy Lianga06f2152018-05-24 15:33:31 -0400175 break;
176 case kMetal_IntrinsicKind:
177 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
178 switch ((MetalIntrinsic) intrinsicId) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500179 case kEqual_MetalIntrinsic:
180 this->write(" == ");
181 break;
182 case kNotEqual_MetalIntrinsic:
183 this->write(" != ");
184 break;
Timothy Lianga06f2152018-05-24 15:33:31 -0400185 case kLessThan_MetalIntrinsic:
186 this->write(" < ");
187 break;
188 case kLessThanEqual_MetalIntrinsic:
189 this->write(" <= ");
190 break;
191 case kGreaterThan_MetalIntrinsic:
192 this->write(" > ");
193 break;
194 case kGreaterThanEqual_MetalIntrinsic:
195 this->write(" >= ");
196 break;
197 default:
198 ABORT("unsupported metal intrinsic kind");
199 }
200 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
201 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400202 default:
203 ABORT("unsupported intrinsic kind");
204 }
205}
206
Ethan Nicholascc305772017-10-13 16:17:45 -0400207void MetalCodeGenerator::writeFunctionCall(const FunctionCall& c) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400208 const auto& entry = fIntrinsicMap.find(c.fFunction.fName);
209 if (entry != fIntrinsicMap.end()) {
210 this->writeIntrinsicCall(c);
211 return;
212 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400213 if (c.fFunction.fBuiltin && "atan" == c.fFunction.fName && 2 == c.fArguments.size()) {
214 this->write("atan2");
Timothy Lianga06f2152018-05-24 15:33:31 -0400215 } else if (c.fFunction.fBuiltin && "inversesqrt" == c.fFunction.fName) {
216 this->write("rsqrt");
Chris Daltondba7aab2018-11-15 10:57:49 -0500217 } else if (c.fFunction.fBuiltin && "inverse" == c.fFunction.fName) {
218 SkASSERT(c.fArguments.size() == 1);
219 this->writeInverseHack(*c.fArguments[0]);
Timothy Liang7d637782018-06-05 09:58:07 -0400220 } else if (c.fFunction.fBuiltin && "dFdx" == c.fFunction.fName) {
221 this->write("dfdx");
222 } else if (c.fFunction.fBuiltin && "dFdy" == c.fFunction.fName) {
Chris Daltonb8af5ad2019-02-25 14:54:21 -0700223 // Flipping Y also negates the Y derivatives.
224 this->write((fProgram.fSettings.fFlipY) ? "-dfdy" : "dfdy");
Ethan Nicholascc305772017-10-13 16:17:45 -0400225 } else {
Timothy Liang651286f2018-06-07 09:55:33 -0400226 this->writeName(c.fFunction.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400227 }
228 this->write("(");
229 const char* separator = "";
230 if (this->requirements(c.fFunction) & kInputs_Requirement) {
231 this->write("_in");
232 separator = ", ";
233 }
234 if (this->requirements(c.fFunction) & kOutputs_Requirement) {
235 this->write(separator);
236 this->write("_out");
237 separator = ", ";
238 }
239 if (this->requirements(c.fFunction) & kUniforms_Requirement) {
240 this->write(separator);
241 this->write("_uniforms");
242 separator = ", ";
243 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400244 if (this->requirements(c.fFunction) & kGlobals_Requirement) {
245 this->write(separator);
246 this->write("_globals");
247 separator = ", ";
248 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400249 if (this->requirements(c.fFunction) & kFragCoord_Requirement) {
250 this->write(separator);
251 this->write("_fragCoord");
252 separator = ", ";
253 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400254 for (size_t i = 0; i < c.fArguments.size(); ++i) {
255 const Expression& arg = *c.fArguments[i];
256 this->write(separator);
257 separator = ", ";
258 if (c.fFunction.fParameters[i]->fModifiers.fFlags & Modifiers::kOut_Flag) {
259 this->write("&");
260 }
261 this->writeExpression(arg, kSequence_Precedence);
262 }
263 this->write(")");
264}
265
Chris Daltondba7aab2018-11-15 10:57:49 -0500266void MetalCodeGenerator::writeInverseHack(const Expression& mat) {
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500267 String typeName = mat.fType.name();
268 String name = typeName + "_inverse";
269 if (mat.fType == *fContext.fFloat2x2_Type || mat.fType == *fContext.fHalf2x2_Type) {
Chris Daltondba7aab2018-11-15 10:57:49 -0500270 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
271 fWrittenIntrinsics.insert(name);
272 fExtraFunctions.writeText((
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500273 typeName + " " + name + "(" + typeName + " m) {"
Chris Daltondba7aab2018-11-15 10:57:49 -0500274 " return float2x2(m[1][1], -m[0][1], -m[1][0], m[0][0]) * (1/determinant(m));"
275 "}"
276 ).c_str());
277 }
278 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500279 else if (mat.fType == *fContext.fFloat3x3_Type || mat.fType == *fContext.fHalf3x3_Type) {
280 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
281 fWrittenIntrinsics.insert(name);
282 fExtraFunctions.writeText((
283 typeName + " " + name + "(" + typeName + " m) {"
284 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];"
285 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];"
286 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];"
287 " float b01 = a22 * a11 - a12 * a21;"
288 " float b11 = -a22 * a10 + a12 * a20;"
289 " float b21 = a21 * a10 - a11 * a20;"
290 " float det = a00 * b01 + a01 * b11 + a02 * b21;"
291 " return " + typeName +
292 " (b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),"
293 " b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),"
294 " b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) * "
295 " (1/det);"
296 "}"
297 ).c_str());
298 }
299 }
300 else if (mat.fType == *fContext.fFloat4x4_Type || mat.fType == *fContext.fHalf4x4_Type) {
301 if (fWrittenIntrinsics.find(name) == fWrittenIntrinsics.end()) {
302 fWrittenIntrinsics.insert(name);
303 fExtraFunctions.writeText((
304 typeName + " " + name + "(" + typeName + " m) {"
305 " float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3];"
306 " float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3];"
307 " float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3];"
308 " float a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3];"
309 " float b00 = a00 * a11 - a01 * a10;"
310 " float b01 = a00 * a12 - a02 * a10;"
311 " float b02 = a00 * a13 - a03 * a10;"
312 " float b03 = a01 * a12 - a02 * a11;"
313 " float b04 = a01 * a13 - a03 * a11;"
314 " float b05 = a02 * a13 - a03 * a12;"
315 " float b06 = a20 * a31 - a21 * a30;"
316 " float b07 = a20 * a32 - a22 * a30;"
317 " float b08 = a20 * a33 - a23 * a30;"
318 " float b09 = a21 * a32 - a22 * a31;"
319 " float b10 = a21 * a33 - a23 * a31;"
320 " float b11 = a22 * a33 - a23 * a32;"
321 " float det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - "
322 " b04 * b07 + b05 * b06;"
323 " return " + typeName + "(a11 * b11 - a12 * b10 + a13 * b09,"
324 " a02 * b10 - a01 * b11 - a03 * b09,"
325 " a31 * b05 - a32 * b04 + a33 * b03,"
326 " a22 * b04 - a21 * b05 - a23 * b03,"
327 " a12 * b08 - a10 * b11 - a13 * b07,"
328 " a00 * b11 - a02 * b08 + a03 * b07,"
329 " a32 * b02 - a30 * b05 - a33 * b01,"
330 " a20 * b05 - a22 * b02 + a23 * b01,"
331 " a10 * b10 - a11 * b08 + a13 * b06,"
332 " a01 * b08 - a00 * b10 - a03 * b06,"
333 " a30 * b04 - a31 * b02 + a33 * b00,"
334 " a21 * b02 - a20 * b04 - a23 * b00,"
335 " a11 * b07 - a10 * b09 - a12 * b06,"
336 " a00 * b09 - a01 * b07 + a02 * b06,"
337 " a31 * b01 - a30 * b03 - a32 * b00,"
338 " a20 * b03 - a21 * b01 + a22 * b00) / det;"
339 "}"
340 ).c_str());
341 }
342 }
Chris Daltondba7aab2018-11-15 10:57:49 -0500343 this->write(name);
344}
345
Timothy Liang6403b0e2018-05-17 10:40:04 -0400346void MetalCodeGenerator::writeSpecialIntrinsic(const FunctionCall & c, SpecialIntrinsic kind) {
347 switch (kind) {
348 case kTexture_SpecialIntrinsic:
Timothy Liangee84fe12018-05-18 14:38:19 -0400349 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
Timothy Lianga06f2152018-05-24 15:33:31 -0400350 this->write(".sample(");
351 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
352 this->write(SAMPLER_SUFFIX);
353 this->write(", ");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400354 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
Timothy Liangee84fe12018-05-18 14:38:19 -0400355 if (c.fArguments[1]->fType == *fContext.fFloat3_Type) {
356 this->write(".xy)"); // FIXME - add projection functionality
357 } else {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400358 SkASSERT(c.fArguments[1]->fType == *fContext.fFloat2_Type);
Timothy Liangee84fe12018-05-18 14:38:19 -0400359 this->write(")");
360 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400361 break;
Timothy Liang651286f2018-06-07 09:55:33 -0400362 case kMod_SpecialIntrinsic:
363 // fmod(x, y) in metal calculates x - y * trunc(x / y) instead of x - y * floor(x / y)
364 this->write("((");
365 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
366 this->write(") - (");
367 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
368 this->write(") * floor((");
369 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
370 this->write(") / (");
371 this->writeExpression(*c.fArguments[1], kSequence_Precedence);
372 this->write(")))");
373 break;
Ethan Nicholasffdc3e62019-09-19 16:58:33 -0400374 case kUnpremul_SpecialIntrinsic: {
375 String tmpVar1 = "unpremul" + to_string(fVarCount++);
376 this->fFunctionHeader += String(" ") +
377 this->getTypeName(c.fArguments[0]->fType) + " " + tmpVar1 +
378 ";";
379 String tmpVar2 = "unpremulNonZeroAlpha" + to_string(fVarCount++);
380 this->fFunctionHeader += String(" ") +
381 this->getTypeName(c.fArguments[0]->fType.componentType()) +
382 " " + tmpVar2 + ";";
383 this->write("(" + tmpVar1 + " = ");
384 this->writeExpression(*c.fArguments[0], kSequence_Precedence);
385 this->write(", " + tmpVar2 + " = max(" + tmpVar1 + ".a, " +
386 to_string(SKSL_UNPREMUL_MIN) + "), " +
387 this->getTypeName(*fContext.fHalf4_Type) + "(" + tmpVar1 +
388 ".rgb / " + tmpVar2 + ", " + tmpVar2 + "))");
389 return;
390 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400391 default:
392 ABORT("unsupported special intrinsic kind");
393 }
394}
395
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500396// If it hasn't already been written, writes a constructor for 'matrix' which takes a single value
397// of type 'arg'.
398String MetalCodeGenerator::getMatrixConstructHelper(const Type& matrix, const Type& arg) {
399 String key = matrix.name() + arg.name();
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500400 auto found = fHelpers.find(key);
401 if (found != fHelpers.end()) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500402 return found->second;
Ethan Nicholascc305772017-10-13 16:17:45 -0400403 }
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500404 String name;
405 int columns = matrix.columns();
406 int rows = matrix.rows();
407 if (arg.isNumber()) {
408 // creating a matrix from a single scalar value
409 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float";
410 fExtraFunctions.printf("float%dx%d %s(float x) {\n",
411 columns, rows, name.c_str());
412 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
413 for (int i = 0; i < columns; ++i) {
414 if (i > 0) {
415 fExtraFunctions.writeText(", ");
416 }
417 fExtraFunctions.printf("float%d(", rows);
418 for (int j = 0; j < rows; ++j) {
419 if (j > 0) {
420 fExtraFunctions.writeText(", ");
421 }
422 if (i == j) {
423 fExtraFunctions.writeText("x");
424 } else {
425 fExtraFunctions.writeText("0");
426 }
427 }
428 fExtraFunctions.writeText(")");
429 }
430 fExtraFunctions.writeText(");\n}\n");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500431 } else if (arg.kind() == Type::kMatrix_Kind) {
432 // creating a matrix from another matrix
433 int argColumns = arg.columns();
434 int argRows = arg.rows();
435 name = "float" + to_string(columns) + "x" + to_string(rows) + "_from_float" +
436 to_string(argColumns) + "x" + to_string(argRows);
437 fExtraFunctions.printf("float%dx%d %s(float%dx%d m) {\n",
438 columns, rows, name.c_str(), argColumns, argRows);
439 fExtraFunctions.printf(" return float%dx%d(", columns, rows);
440 for (int i = 0; i < columns; ++i) {
441 if (i > 0) {
442 fExtraFunctions.writeText(", ");
443 }
444 fExtraFunctions.printf("float%d(", rows);
445 for (int j = 0; j < rows; ++j) {
446 if (j > 0) {
447 fExtraFunctions.writeText(", ");
448 }
449 if (i < argColumns && j < argRows) {
450 fExtraFunctions.printf("m[%d][%d]", i, j);
451 } else {
452 fExtraFunctions.writeText("0");
453 }
454 }
455 fExtraFunctions.writeText(")");
456 }
457 fExtraFunctions.writeText(");\n}\n");
458 } else if (matrix.rows() == 2 && matrix.columns() == 2 && arg == *fContext.fFloat4_Type) {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500459 // float2x2(float4) doesn't work, need to split it into float2x2(float2, float2)
460 name = "float2x2_from_float4";
461 fExtraFunctions.printf(
462 "float2x2 %s(float4 v) {\n"
463 " return float2x2(float2(v[0], v[1]), float2(v[2], v[3]));\n"
464 "}\n",
465 name.c_str()
466 );
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500467 } else {
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500468 SkASSERT(false);
469 name = "<error>";
470 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500471 fHelpers[key] = name;
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500472 return name;
473}
474
475bool MetalCodeGenerator::canCoerce(const Type& t1, const Type& t2) {
476 if (t1.columns() != t2.columns() || t1.rows() != t2.rows()) {
477 return false;
478 }
479 if (t1.columns() > 1) {
480 return this->canCoerce(t1.componentType(), t2.componentType());
481 }
Ethan Nicholase1f55022019-02-05 17:17:40 -0500482 return t1.isFloat() && t2.isFloat();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500483}
484
485void MetalCodeGenerator::writeConstructor(const Constructor& c, Precedence parentPrecedence) {
486 if (c.fArguments.size() == 1 && this->canCoerce(c.fType, c.fArguments[0]->fType)) {
487 this->writeExpression(*c.fArguments[0], parentPrecedence);
488 return;
489 }
490 if (c.fType.kind() == Type::kMatrix_Kind && c.fArguments.size() == 1) {
491 const Expression& arg = *c.fArguments[0];
492 String name = this->getMatrixConstructHelper(c.fType, arg.fType);
493 this->write(name);
494 this->write("(");
495 this->writeExpression(arg, kSequence_Precedence);
496 this->write(")");
497 } else {
498 this->writeType(c.fType);
499 this->write("(");
500 const char* separator = "";
501 int scalarCount = 0;
502 for (const auto& arg : c.fArguments) {
503 this->write(separator);
504 separator = ", ";
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500505 if (Type::kMatrix_Kind == c.fType.kind() && arg->fType.columns() != c.fType.rows()) {
506 // merge scalars and smaller vectors together
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500507 if (!scalarCount) {
508 this->writeType(c.fType.componentType());
509 this->write(to_string(c.fType.rows()));
510 this->write("(");
511 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500512 scalarCount += arg->fType.columns();
Ethan Nicholas842d31b2019-01-22 10:59:11 -0500513 }
514 this->writeExpression(*arg, kSequence_Precedence);
515 if (scalarCount && scalarCount == c.fType.rows()) {
516 this->write(")");
517 scalarCount = 0;
518 }
519 }
520 this->write(")");
521 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400522}
523
524void MetalCodeGenerator::writeFragCoord() {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400525 if (fRTHeightName.length()) {
526 this->write("float4(_fragCoord.x, ");
527 this->write(fRTHeightName.c_str());
528 this->write(" - _fragCoord.y, 0.0, _fragCoord.w)");
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500529 } else {
530 this->write("float4(_fragCoord.x, _fragCoord.y, 0.0, _fragCoord.w)");
531 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400532}
533
534void MetalCodeGenerator::writeVariableReference(const VariableReference& ref) {
535 switch (ref.fVariable.fModifiers.fLayout.fBuiltin) {
536 case SK_FRAGCOLOR_BUILTIN:
Timothy Liang7d637782018-06-05 09:58:07 -0400537 this->write("_out->sk_FragColor");
Ethan Nicholascc305772017-10-13 16:17:45 -0400538 break;
Timothy Liang6403b0e2018-05-17 10:40:04 -0400539 case SK_FRAGCOORD_BUILTIN:
540 this->writeFragCoord();
541 break;
Timothy Liangdc89f192018-06-13 09:20:31 -0400542 case SK_VERTEXID_BUILTIN:
543 this->write("sk_VertexID");
544 break;
545 case SK_INSTANCEID_BUILTIN:
546 this->write("sk_InstanceID");
547 break;
Timothy Liang7b8875d2018-08-10 09:42:31 -0400548 case SK_CLOCKWISE_BUILTIN:
549 // We'd set the front facing winding in the MTLRenderCommandEncoder to be counter
550 // clockwise to match Skia convention. This is also the default in MoltenVK.
551 this->write(fProgram.fSettings.fFlipY ? "_frontFacing" : "(!_frontFacing)");
552 break;
Ethan Nicholascc305772017-10-13 16:17:45 -0400553 default:
554 if (Variable::kGlobal_Storage == ref.fVariable.fStorage) {
555 if (ref.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
556 this->write("_in.");
557 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400558 this->write("_out->");
Timothy Lianga06f2152018-05-24 15:33:31 -0400559 } else if (ref.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
560 ref.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400561 this->write("_uniforms.");
562 } else {
Timothy Liangee84fe12018-05-18 14:38:19 -0400563 this->write("_globals->");
Ethan Nicholascc305772017-10-13 16:17:45 -0400564 }
565 }
Timothy Liang651286f2018-06-07 09:55:33 -0400566 this->writeName(ref.fVariable.fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400567 }
568}
569
570void MetalCodeGenerator::writeIndexExpression(const IndexExpression& expr) {
571 this->writeExpression(*expr.fBase, kPostfix_Precedence);
572 this->write("[");
573 this->writeExpression(*expr.fIndex, kTopLevel_Precedence);
574 this->write("]");
575}
576
577void MetalCodeGenerator::writeFieldAccess(const FieldAccess& f) {
Timothy Liang7d637782018-06-05 09:58:07 -0400578 const Type::Field* field = &f.fBase->fType.fields()[f.fFieldIndex];
Ethan Nicholascc305772017-10-13 16:17:45 -0400579 if (FieldAccess::kDefault_OwnerKind == f.fOwnerKind) {
580 this->writeExpression(*f.fBase, kPostfix_Precedence);
581 this->write(".");
582 }
Timothy Liang7d637782018-06-05 09:58:07 -0400583 switch (field->fModifiers.fLayout.fBuiltin) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400584 case SK_CLIPDISTANCE_BUILTIN:
585 this->write("gl_ClipDistance");
586 break;
587 case SK_POSITION_BUILTIN:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400588 this->write("_out->sk_Position");
Ethan Nicholascc305772017-10-13 16:17:45 -0400589 break;
590 default:
Timothy Liang7d637782018-06-05 09:58:07 -0400591 if (field->fName == "sk_PointSize") {
592 this->write("_out->sk_PointSize");
593 } else {
594 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
595 this->write("_globals->");
596 this->write(fInterfaceBlockNameMap[fInterfaceBlockMap[field]]);
597 this->write("->");
598 }
Timothy Liang651286f2018-06-07 09:55:33 -0400599 this->writeName(field->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400600 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400601 }
602}
603
604void MetalCodeGenerator::writeSwizzle(const Swizzle& swizzle) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500605 int last = swizzle.fComponents.back();
606 if (last == SKSL_SWIZZLE_0 || last == SKSL_SWIZZLE_1) {
607 this->writeType(swizzle.fType);
608 this->write("(");
609 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400610 this->writeExpression(*swizzle.fBase, kPostfix_Precedence);
611 this->write(".");
612 for (int c : swizzle.fComponents) {
Ethan Nicholas5476f2e2019-03-07 15:11:31 -0500613 if (c >= 0) {
614 this->write(&("x\0y\0z\0w\0"[c * 2]));
615 }
616 }
617 if (last == SKSL_SWIZZLE_0) {
618 this->write(", 0)");
619 }
620 else if (last == SKSL_SWIZZLE_1) {
621 this->write(", 1)");
Ethan Nicholascc305772017-10-13 16:17:45 -0400622 }
623}
624
625MetalCodeGenerator::Precedence MetalCodeGenerator::GetBinaryPrecedence(Token::Kind op) {
626 switch (op) {
627 case Token::STAR: // fall through
628 case Token::SLASH: // fall through
629 case Token::PERCENT: return MetalCodeGenerator::kMultiplicative_Precedence;
630 case Token::PLUS: // fall through
631 case Token::MINUS: return MetalCodeGenerator::kAdditive_Precedence;
632 case Token::SHL: // fall through
633 case Token::SHR: return MetalCodeGenerator::kShift_Precedence;
634 case Token::LT: // fall through
635 case Token::GT: // fall through
636 case Token::LTEQ: // fall through
637 case Token::GTEQ: return MetalCodeGenerator::kRelational_Precedence;
638 case Token::EQEQ: // fall through
639 case Token::NEQ: return MetalCodeGenerator::kEquality_Precedence;
640 case Token::BITWISEAND: return MetalCodeGenerator::kBitwiseAnd_Precedence;
641 case Token::BITWISEXOR: return MetalCodeGenerator::kBitwiseXor_Precedence;
642 case Token::BITWISEOR: return MetalCodeGenerator::kBitwiseOr_Precedence;
643 case Token::LOGICALAND: return MetalCodeGenerator::kLogicalAnd_Precedence;
644 case Token::LOGICALXOR: return MetalCodeGenerator::kLogicalXor_Precedence;
645 case Token::LOGICALOR: return MetalCodeGenerator::kLogicalOr_Precedence;
646 case Token::EQ: // fall through
647 case Token::PLUSEQ: // fall through
648 case Token::MINUSEQ: // fall through
649 case Token::STAREQ: // fall through
650 case Token::SLASHEQ: // fall through
651 case Token::PERCENTEQ: // fall through
652 case Token::SHLEQ: // fall through
653 case Token::SHREQ: // fall through
654 case Token::LOGICALANDEQ: // fall through
655 case Token::LOGICALXOREQ: // fall through
656 case Token::LOGICALOREQ: // fall through
657 case Token::BITWISEANDEQ: // fall through
658 case Token::BITWISEXOREQ: // fall through
659 case Token::BITWISEOREQ: return MetalCodeGenerator::kAssignment_Precedence;
660 case Token::COMMA: return MetalCodeGenerator::kSequence_Precedence;
661 default: ABORT("unsupported binary operator");
662 }
663}
664
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500665void MetalCodeGenerator::writeMatrixTimesEqualHelper(const Type& left, const Type& right,
666 const Type& result) {
667 String key = "TimesEqual" + left.name() + right.name();
668 if (fHelpers.find(key) == fHelpers.end()) {
669 fExtraFunctions.printf("%s operator*=(thread %s& left, thread const %s& right) {\n"
670 " left = left * right;\n"
671 " return left;\n"
672 "}", result.name().c_str(), left.name().c_str(),
673 right.name().c_str());
674 }
675}
676
Ethan Nicholascc305772017-10-13 16:17:45 -0400677void MetalCodeGenerator::writeBinaryExpression(const BinaryExpression& b,
678 Precedence parentPrecedence) {
679 Precedence precedence = GetBinaryPrecedence(b.fOperator);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500680 bool needParens = precedence >= parentPrecedence;
681 switch (b.fOperator) {
682 case Token::EQEQ:
683 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
684 this->write("all");
685 needParens = true;
686 }
687 break;
688 case Token::NEQ:
689 if (b.fLeft->fType.kind() == Type::kVector_Kind) {
Jim Van Verth36477b42019-04-11 14:57:30 -0400690 this->write("any");
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500691 needParens = true;
692 }
693 break;
694 default:
695 break;
696 }
697 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400698 this->write("(");
699 }
700 if (Compiler::IsAssignment(b.fOperator) &&
701 Expression::kVariableReference_Kind == b.fLeft->fKind &&
702 Variable::kParameter_Storage == ((VariableReference&) *b.fLeft).fVariable.fStorage &&
703 (((VariableReference&) *b.fLeft).fVariable.fModifiers.fFlags & Modifiers::kOut_Flag)) {
704 // writing to an out parameter. Since we have to turn those into pointers, we have to
705 // dereference it here.
706 this->write("*");
707 }
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500708 if (b.fOperator == Token::STAREQ && b.fLeft->fType.kind() == Type::kMatrix_Kind &&
709 b.fRight->fType.kind() == Type::kMatrix_Kind) {
710 this->writeMatrixTimesEqualHelper(b.fLeft->fType, b.fRight->fType, b.fType);
711 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400712 this->writeExpression(*b.fLeft, precedence);
713 if (b.fOperator != Token::EQ && Compiler::IsAssignment(b.fOperator) &&
714 Expression::kSwizzle_Kind == b.fLeft->fKind && !b.fLeft->hasSideEffects()) {
715 // This doesn't compile in Metal:
716 // float4 x = float4(1);
717 // x.xy *= float2x2(...);
718 // with the error message "non-const reference cannot bind to vector element",
719 // but switching it to x.xy = x.xy * float2x2(...) fixes it. We perform this tranformation
720 // as long as the LHS has no side effects, and hope for the best otherwise.
721 this->write(" = ");
722 this->writeExpression(*b.fLeft, kAssignment_Precedence);
723 this->write(" ");
724 String op = Compiler::OperatorName(b.fOperator);
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400725 SkASSERT(op.endsWith("="));
Ethan Nicholascc305772017-10-13 16:17:45 -0400726 this->write(op.substr(0, op.size() - 1).c_str());
727 this->write(" ");
728 } else {
729 this->write(String(" ") + Compiler::OperatorName(b.fOperator) + " ");
730 }
731 this->writeExpression(*b.fRight, precedence);
Ethan Nicholas0dc80872019-02-08 15:46:24 -0500732 if (needParens) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400733 this->write(")");
734 }
735}
736
737void MetalCodeGenerator::writeTernaryExpression(const TernaryExpression& t,
738 Precedence parentPrecedence) {
739 if (kTernary_Precedence >= parentPrecedence) {
740 this->write("(");
741 }
742 this->writeExpression(*t.fTest, kTernary_Precedence);
743 this->write(" ? ");
744 this->writeExpression(*t.fIfTrue, kTernary_Precedence);
745 this->write(" : ");
746 this->writeExpression(*t.fIfFalse, kTernary_Precedence);
747 if (kTernary_Precedence >= parentPrecedence) {
748 this->write(")");
749 }
750}
751
752void MetalCodeGenerator::writePrefixExpression(const PrefixExpression& p,
753 Precedence parentPrecedence) {
754 if (kPrefix_Precedence >= parentPrecedence) {
755 this->write("(");
756 }
757 this->write(Compiler::OperatorName(p.fOperator));
758 this->writeExpression(*p.fOperand, kPrefix_Precedence);
759 if (kPrefix_Precedence >= parentPrecedence) {
760 this->write(")");
761 }
762}
763
764void MetalCodeGenerator::writePostfixExpression(const PostfixExpression& p,
765 Precedence parentPrecedence) {
766 if (kPostfix_Precedence >= parentPrecedence) {
767 this->write("(");
768 }
769 this->writeExpression(*p.fOperand, kPostfix_Precedence);
770 this->write(Compiler::OperatorName(p.fOperator));
771 if (kPostfix_Precedence >= parentPrecedence) {
772 this->write(")");
773 }
774}
775
776void MetalCodeGenerator::writeBoolLiteral(const BoolLiteral& b) {
777 this->write(b.fValue ? "true" : "false");
778}
779
780void MetalCodeGenerator::writeIntLiteral(const IntLiteral& i) {
781 if (i.fType == *fContext.fUInt_Type) {
782 this->write(to_string(i.fValue & 0xffffffff) + "u");
783 } else {
784 this->write(to_string((int32_t) i.fValue));
785 }
786}
787
788void MetalCodeGenerator::writeFloatLiteral(const FloatLiteral& f) {
789 this->write(to_string(f.fValue));
790}
791
792void MetalCodeGenerator::writeSetting(const Setting& s) {
793 ABORT("internal error; setting was not folded to a constant during compilation\n");
794}
795
796void MetalCodeGenerator::writeFunction(const FunctionDefinition& f) {
Ethan Nicholasf931e402019-07-26 15:40:33 -0400797 fRTHeightName = fProgram.fInputs.fRTHeight ? "_globals->_anonInterface0->u_skRTHeight" : "";
Ethan Nicholascc305772017-10-13 16:17:45 -0400798 const char* separator = "";
799 if ("main" == f.fDeclaration.fName) {
800 switch (fProgram.fKind) {
801 case Program::kFragment_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400802#ifdef SK_MOLTENVK
803 this->write("fragment Outputs main0");
804#else
805 this->write("fragment Outputs fragmentMain");
806#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400807 break;
808 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400809#ifdef SK_MOLTENVK
Timothy Lianga06f2152018-05-24 15:33:31 -0400810 this->write("vertex Outputs main0");
Timothy Liangb8eeb802018-07-23 16:46:16 -0400811#else
812 this->write("vertex Outputs vertexMain");
813#endif
Ethan Nicholascc305772017-10-13 16:17:45 -0400814 break;
815 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400816 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400817 }
818 this->write("(Inputs _in [[stage_in]]");
819 if (-1 != fUniformBuffer) {
820 this->write(", constant Uniforms& _uniforms [[buffer(" +
821 to_string(fUniformBuffer) + ")]]");
822 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400823 for (const auto& e : fProgram) {
824 if (ProgramElement::kVar_Kind == e.fKind) {
825 VarDeclarations& decls = (VarDeclarations&) e;
826 if (!decls.fVars.size()) {
827 continue;
828 }
Timothy Liangee84fe12018-05-18 14:38:19 -0400829 for (const auto& stmt: decls.fVars) {
Timothy Liang6403b0e2018-05-17 10:40:04 -0400830 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -0400831 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
Timothy Liang7d637782018-06-05 09:58:07 -0400832 this->write(", texture2d<float> "); // FIXME - support other texture types
Timothy Liang651286f2018-06-07 09:55:33 -0400833 this->writeName(var.fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400834 this->write("[[texture(");
Timothy Lianga06f2152018-05-24 15:33:31 -0400835 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
836 this->write(")]]");
837 this->write(", sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -0400838 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400839 this->write(SAMPLER_SUFFIX);
840 this->write("[[sampler(");
841 this->write(to_string(var.fVar->fModifiers.fLayout.fBinding));
Timothy Liangee84fe12018-05-18 14:38:19 -0400842 this->write(")]]");
843 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400844 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400845 } else if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
846 InterfaceBlock& intf = (InterfaceBlock&) e;
847 if ("sk_PerVertex" == intf.fTypeName) {
848 continue;
849 }
850 this->write(", constant ");
851 this->writeType(intf.fVariable.fType);
852 this->write("& " );
853 this->write(fInterfaceBlockNameMap[&intf]);
854 this->write(" [[buffer(");
Timothy Liang057c3902018-08-08 10:48:45 -0400855#ifdef SK_MOLTENVK
Timothy Liang7d637782018-06-05 09:58:07 -0400856 this->write(to_string(intf.fVariable.fModifiers.fLayout.fSet));
Timothy Liang057c3902018-08-08 10:48:45 -0400857#else
858 this->write(to_string(intf.fVariable.fModifiers.fLayout.fBinding));
859#endif
Timothy Lianga06f2152018-05-24 15:33:31 -0400860 this->write(")]]");
Timothy Liang6403b0e2018-05-17 10:40:04 -0400861 }
862 }
Jim Van Verth6bc650e2019-02-07 14:53:23 -0500863 if (fProgram.fKind == Program::kFragment_Kind) {
864 if (fProgram.fInputs.fRTHeight && fInterfaceBlockNameMap.empty()) {
Timothy Liang5422f9a2018-08-10 10:57:55 -0400865#ifdef SK_MOLTENVK
866 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(0)]]");
867#else
868 this->write(", constant sksl_synthetic_uniforms& _anonInterface0 [[buffer(1)]]");
869#endif
Ethan Nicholasf931e402019-07-26 15:40:33 -0400870 fRTHeightName = "_anonInterface0.u_skRTHeight";
Timothy Liang5422f9a2018-08-10 10:57:55 -0400871 }
Timothy Liang7b8875d2018-08-10 09:42:31 -0400872 this->write(", bool _frontFacing [[front_facing]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400873 this->write(", float4 _fragCoord [[position]]");
Timothy Liangdc89f192018-06-13 09:20:31 -0400874 } else if (fProgram.fKind == Program::kVertex_Kind) {
875 this->write(", uint sk_VertexID [[vertex_id]], uint sk_InstanceID [[instance_id]]");
Timothy Liang7d637782018-06-05 09:58:07 -0400876 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400877 separator = ", ";
878 } else {
879 this->writeType(f.fDeclaration.fReturnType);
Timothy Liang651286f2018-06-07 09:55:33 -0400880 this->write(" ");
881 this->writeName(f.fDeclaration.fName);
882 this->write("(");
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400883 Requirements requirements = this->requirements(f.fDeclaration);
884 if (requirements & kInputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400885 this->write("Inputs _in");
886 separator = ", ";
887 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400888 if (requirements & kOutputs_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400889 this->write(separator);
Timothy Liangee84fe12018-05-18 14:38:19 -0400890 this->write("thread Outputs* _out");
Ethan Nicholascc305772017-10-13 16:17:45 -0400891 separator = ", ";
892 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400893 if (requirements & kUniforms_Requirement) {
Ethan Nicholascc305772017-10-13 16:17:45 -0400894 this->write(separator);
895 this->write("Uniforms _uniforms");
896 separator = ", ";
897 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400898 if (requirements & kGlobals_Requirement) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400899 this->write(separator);
900 this->write("thread Globals* _globals");
901 separator = ", ";
902 }
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -0400903 if (requirements & kFragCoord_Requirement) {
904 this->write(separator);
905 this->write("float4 _fragCoord");
906 separator = ", ";
907 }
Ethan Nicholascc305772017-10-13 16:17:45 -0400908 }
909 for (const auto& param : f.fDeclaration.fParameters) {
910 this->write(separator);
911 separator = ", ";
912 this->writeModifiers(param->fModifiers, false);
913 std::vector<int> sizes;
914 const Type* type = &param->fType;
915 while (Type::kArray_Kind == type->kind()) {
916 sizes.push_back(type->columns());
917 type = &type->componentType();
918 }
919 this->writeType(*type);
920 if (param->fModifiers.fFlags & Modifiers::kOut_Flag) {
921 this->write("*");
922 }
Timothy Liang651286f2018-06-07 09:55:33 -0400923 this->write(" ");
924 this->writeName(param->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -0400925 for (int s : sizes) {
926 if (s <= 0) {
927 this->write("[]");
928 } else {
929 this->write("[" + to_string(s) + "]");
930 }
931 }
932 }
933 this->writeLine(") {");
934
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400935 SkASSERT(!fProgram.fSettings.fFragColorIsInOut);
Brian Salomondc092132018-04-04 10:14:16 -0400936
Ethan Nicholascc305772017-10-13 16:17:45 -0400937 if ("main" == f.fDeclaration.fName) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400938 if (fNeedsGlobalStructInit) {
939 this->writeLine(" Globals globalStruct;");
940 this->writeLine(" thread Globals* _globals = &globalStruct;");
Timothy Liang7d637782018-06-05 09:58:07 -0400941 for (const auto& intf: fInterfaceBlockNameMap) {
942 const auto& intfName = intf.second;
943 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400944 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400945 this->write(" = &");
Timothy Liang651286f2018-06-07 09:55:33 -0400946 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -0400947 this->write(";\n");
948 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400949 for (const auto& var: fInitNonConstGlobalVars) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400950 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400951 this->writeName(var->fVar->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400952 this->write(" = ");
953 this->writeVarInitializer(*var->fVar, *var->fValue);
954 this->writeLine(";");
955 }
Timothy Lianga06f2152018-05-24 15:33:31 -0400956 for (const auto& texture: fTextures) {
Timothy Liangee84fe12018-05-18 14:38:19 -0400957 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400958 this->writeName(texture->fName);
Timothy Liangee84fe12018-05-18 14:38:19 -0400959 this->write(" = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400960 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400961 this->write(";\n");
962 this->write(" _globals->");
Timothy Liang651286f2018-06-07 09:55:33 -0400963 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400964 this->write(SAMPLER_SUFFIX);
965 this->write(" = ");
Timothy Liang651286f2018-06-07 09:55:33 -0400966 this->writeName(texture->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -0400967 this->write(SAMPLER_SUFFIX);
Timothy Liangee84fe12018-05-18 14:38:19 -0400968 this->write(";\n");
969 }
Timothy Liang6403b0e2018-05-17 10:40:04 -0400970 }
Timothy Liang7d637782018-06-05 09:58:07 -0400971 this->writeLine(" Outputs _outputStruct;");
972 this->writeLine(" thread Outputs* _out = &_outputStruct;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400973 }
974 fFunctionHeader = "";
975 OutputStream* oldOut = fOut;
976 StringStream buffer;
977 fOut = &buffer;
978 fIndentation++;
979 this->writeStatements(((Block&) *f.fBody).fStatements);
980 if ("main" == f.fDeclaration.fName) {
981 switch (fProgram.fKind) {
982 case Program::kFragment_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -0400983 this->writeLine("return *_out;");
Ethan Nicholascc305772017-10-13 16:17:45 -0400984 break;
985 case Program::kVertex_Kind:
Timothy Liangb8eeb802018-07-23 16:46:16 -0400986 this->writeLine("_out->sk_Position.y = -_out->sk_Position.y;");
Timothy Lianga06f2152018-05-24 15:33:31 -0400987 this->writeLine("return *_out;"); // FIXME - detect if function already has return
Ethan Nicholascc305772017-10-13 16:17:45 -0400988 break;
989 default:
Ethan Nicholasd9d33c32018-06-12 11:05:59 -0400990 SkASSERT(false);
Ethan Nicholascc305772017-10-13 16:17:45 -0400991 }
992 }
993 fIndentation--;
994 this->writeLine("}");
995
996 fOut = oldOut;
997 this->write(fFunctionHeader);
998 this->write(buffer.str());
999}
1000
1001void MetalCodeGenerator::writeModifiers(const Modifiers& modifiers,
1002 bool globalContext) {
1003 if (modifiers.fFlags & Modifiers::kOut_Flag) {
1004 this->write("thread ");
1005 }
1006 if (modifiers.fFlags & Modifiers::kConst_Flag) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001007 this->write("constant ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001008 }
1009}
1010
1011void MetalCodeGenerator::writeInterfaceBlock(const InterfaceBlock& intf) {
1012 if ("sk_PerVertex" == intf.fTypeName) {
1013 return;
1014 }
1015 this->writeModifiers(intf.fVariable.fModifiers, true);
Timothy Liangdc89f192018-06-13 09:20:31 -04001016 this->write("struct ");
Ethan Nicholascc305772017-10-13 16:17:45 -04001017 this->writeLine(intf.fTypeName + " {");
Ethan Nicholascc305772017-10-13 16:17:45 -04001018 const Type* structType = &intf.fVariable.fType;
Timothy Lianga06f2152018-05-24 15:33:31 -04001019 fWrittenStructs.push_back(structType);
Ethan Nicholascc305772017-10-13 16:17:45 -04001020 while (Type::kArray_Kind == structType->kind()) {
1021 structType = &structType->componentType();
1022 }
Timothy Liangdc89f192018-06-13 09:20:31 -04001023 fIndentation++;
1024 writeFields(structType->fields(), structType->fOffset, &intf);
Jim Van Verth3d482992019-02-07 10:48:05 -05001025 if (fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001026 this->writeLine("float u_skRTHeight;");
Ethan Nicholascc305772017-10-13 16:17:45 -04001027 }
1028 fIndentation--;
1029 this->write("}");
1030 if (intf.fInstanceName.size()) {
1031 this->write(" ");
1032 this->write(intf.fInstanceName);
1033 for (const auto& size : intf.fSizes) {
1034 this->write("[");
1035 if (size) {
1036 this->writeExpression(*size, kTopLevel_Precedence);
1037 }
1038 this->write("]");
1039 }
Timothy Lianga06f2152018-05-24 15:33:31 -04001040 fInterfaceBlockNameMap[&intf] = intf.fInstanceName;
1041 } else {
Timothy Liang7d637782018-06-05 09:58:07 -04001042 fInterfaceBlockNameMap[&intf] = "_anonInterface" + to_string(fAnonInterfaceCount++);
Ethan Nicholascc305772017-10-13 16:17:45 -04001043 }
1044 this->writeLine(";");
1045}
1046
Timothy Liangdc89f192018-06-13 09:20:31 -04001047void MetalCodeGenerator::writeFields(const std::vector<Type::Field>& fields, int parentOffset,
1048 const InterfaceBlock* parentIntf) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001049#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001050 MemoryLayout memoryLayout(MemoryLayout::k140_Standard);
Timothy Liang609fbe32018-08-10 16:40:49 -04001051#else
1052 MemoryLayout memoryLayout(MemoryLayout::kMetal_Standard);
1053#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001054 int currentOffset = 0;
1055 for (const auto& field: fields) {
1056 int fieldOffset = field.fModifiers.fLayout.fOffset;
1057 const Type* fieldType = field.fType;
1058 if (fieldOffset != -1) {
1059 if (currentOffset > fieldOffset) {
1060 fErrors.error(parentOffset,
1061 "offset of field '" + field.fName + "' must be at least " +
1062 to_string((int) currentOffset));
1063 } else if (currentOffset < fieldOffset) {
1064 this->write("char pad");
1065 this->write(to_string(fPaddingCount++));
1066 this->write("[");
1067 this->write(to_string(fieldOffset - currentOffset));
1068 this->writeLine("];");
1069 currentOffset = fieldOffset;
1070 }
1071 int alignment = memoryLayout.alignment(*fieldType);
1072 if (fieldOffset % alignment) {
1073 fErrors.error(parentOffset,
1074 "offset of field '" + field.fName + "' must be a multiple of " +
1075 to_string((int) alignment));
1076 }
1077 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001078#ifdef SK_MOLTENVK
Timothy Liangdc89f192018-06-13 09:20:31 -04001079 if (fieldType->kind() == Type::kVector_Kind &&
1080 fieldType->columns() == 3) {
Timothy Liang609fbe32018-08-10 16:40:49 -04001081 SkASSERT(memoryLayout.size(*fieldType) == 3);
Timothy Liangdc89f192018-06-13 09:20:31 -04001082 // Pack all vec3 types so that their size in bytes will match what was expected in the
1083 // original SkSL code since MSL has vec3 sizes equal to 4 * component type, while SkSL
1084 // has vec3 equal to 3 * component type.
Timothy Liang609fbe32018-08-10 16:40:49 -04001085
1086 // FIXME - Packed vectors can't be accessed by swizzles, but can be indexed into. A
1087 // combination of this being a problem which only occurs when using MoltenVK and the
1088 // fact that we haven't swizzled a vec3 yet means that this problem hasn't been
1089 // addressed.
Timothy Liangdc89f192018-06-13 09:20:31 -04001090 this->write(PACKED_PREFIX);
1091 }
Timothy Liang609fbe32018-08-10 16:40:49 -04001092#endif
Timothy Liangdc89f192018-06-13 09:20:31 -04001093 currentOffset += memoryLayout.size(*fieldType);
1094 std::vector<int> sizes;
1095 while (fieldType->kind() == Type::kArray_Kind) {
1096 sizes.push_back(fieldType->columns());
1097 fieldType = &fieldType->componentType();
1098 }
1099 this->writeModifiers(field.fModifiers, false);
1100 this->writeType(*fieldType);
1101 this->write(" ");
1102 this->writeName(field.fName);
1103 for (int s : sizes) {
1104 if (s <= 0) {
1105 this->write("[]");
1106 } else {
1107 this->write("[" + to_string(s) + "]");
1108 }
1109 }
1110 this->writeLine(";");
1111 if (parentIntf) {
1112 fInterfaceBlockMap[&field] = parentIntf;
1113 }
1114 }
1115}
1116
Ethan Nicholascc305772017-10-13 16:17:45 -04001117void MetalCodeGenerator::writeVarInitializer(const Variable& var, const Expression& value) {
1118 this->writeExpression(value, kTopLevel_Precedence);
1119}
1120
Timothy Liang651286f2018-06-07 09:55:33 -04001121void MetalCodeGenerator::writeName(const String& name) {
1122 if (fReservedWords.find(name) != fReservedWords.end()) {
1123 this->write("_"); // adding underscore before name to avoid conflict with reserved words
1124 }
1125 this->write(name);
1126}
1127
Ethan Nicholascc305772017-10-13 16:17:45 -04001128void MetalCodeGenerator::writeVarDeclarations(const VarDeclarations& decl, bool global) {
Ethan Nicholasd9d33c32018-06-12 11:05:59 -04001129 SkASSERT(decl.fVars.size() > 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001130 bool wroteType = false;
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001131 for (const auto& stmt : decl.fVars) {
1132 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liangee84fe12018-05-18 14:38:19 -04001133 if (global && !(var.fVar->fModifiers.fFlags & Modifiers::kConst_Flag)) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001134 continue;
1135 }
1136 if (wroteType) {
1137 this->write(", ");
1138 } else {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001139 this->writeModifiers(var.fVar->fModifiers, global);
Ethan Nicholascc305772017-10-13 16:17:45 -04001140 this->writeType(decl.fBaseType);
1141 this->write(" ");
1142 wroteType = true;
1143 }
Timothy Liang651286f2018-06-07 09:55:33 -04001144 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001145 for (const auto& size : var.fSizes) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001146 this->write("[");
1147 if (size) {
1148 this->writeExpression(*size, kTopLevel_Precedence);
1149 }
1150 this->write("]");
1151 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001152 if (var.fValue) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001153 this->write(" = ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001154 this->writeVarInitializer(*var.fVar, *var.fValue);
Ethan Nicholascc305772017-10-13 16:17:45 -04001155 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001156 }
1157 if (wroteType) {
1158 this->write(";");
1159 }
1160}
1161
1162void MetalCodeGenerator::writeStatement(const Statement& s) {
1163 switch (s.fKind) {
1164 case Statement::kBlock_Kind:
1165 this->writeBlock((Block&) s);
1166 break;
1167 case Statement::kExpression_Kind:
1168 this->writeExpression(*((ExpressionStatement&) s).fExpression, kTopLevel_Precedence);
1169 this->write(";");
1170 break;
1171 case Statement::kReturn_Kind:
1172 this->writeReturnStatement((ReturnStatement&) s);
1173 break;
1174 case Statement::kVarDeclarations_Kind:
1175 this->writeVarDeclarations(*((VarDeclarationsStatement&) s).fDeclaration, false);
1176 break;
1177 case Statement::kIf_Kind:
1178 this->writeIfStatement((IfStatement&) s);
1179 break;
1180 case Statement::kFor_Kind:
1181 this->writeForStatement((ForStatement&) s);
1182 break;
1183 case Statement::kWhile_Kind:
1184 this->writeWhileStatement((WhileStatement&) s);
1185 break;
1186 case Statement::kDo_Kind:
1187 this->writeDoStatement((DoStatement&) s);
1188 break;
1189 case Statement::kSwitch_Kind:
1190 this->writeSwitchStatement((SwitchStatement&) s);
1191 break;
1192 case Statement::kBreak_Kind:
1193 this->write("break;");
1194 break;
1195 case Statement::kContinue_Kind:
1196 this->write("continue;");
1197 break;
1198 case Statement::kDiscard_Kind:
Timothy Lianga06f2152018-05-24 15:33:31 -04001199 this->write("discard_fragment();");
Ethan Nicholascc305772017-10-13 16:17:45 -04001200 break;
1201 case Statement::kNop_Kind:
1202 this->write(";");
1203 break;
1204 default:
1205 ABORT("unsupported statement: %s", s.description().c_str());
1206 }
1207}
1208
1209void MetalCodeGenerator::writeStatements(const std::vector<std::unique_ptr<Statement>>& statements) {
1210 for (const auto& s : statements) {
1211 if (!s->isEmpty()) {
1212 this->writeStatement(*s);
1213 this->writeLine();
1214 }
1215 }
1216}
1217
1218void MetalCodeGenerator::writeBlock(const Block& b) {
1219 this->writeLine("{");
1220 fIndentation++;
1221 this->writeStatements(b.fStatements);
1222 fIndentation--;
1223 this->write("}");
1224}
1225
1226void MetalCodeGenerator::writeIfStatement(const IfStatement& stmt) {
1227 this->write("if (");
1228 this->writeExpression(*stmt.fTest, kTopLevel_Precedence);
1229 this->write(") ");
1230 this->writeStatement(*stmt.fIfTrue);
1231 if (stmt.fIfFalse) {
1232 this->write(" else ");
1233 this->writeStatement(*stmt.fIfFalse);
1234 }
1235}
1236
1237void MetalCodeGenerator::writeForStatement(const ForStatement& f) {
1238 this->write("for (");
1239 if (f.fInitializer && !f.fInitializer->isEmpty()) {
1240 this->writeStatement(*f.fInitializer);
1241 } else {
1242 this->write("; ");
1243 }
1244 if (f.fTest) {
1245 this->writeExpression(*f.fTest, kTopLevel_Precedence);
1246 }
1247 this->write("; ");
1248 if (f.fNext) {
1249 this->writeExpression(*f.fNext, kTopLevel_Precedence);
1250 }
1251 this->write(") ");
1252 this->writeStatement(*f.fStatement);
1253}
1254
1255void MetalCodeGenerator::writeWhileStatement(const WhileStatement& w) {
1256 this->write("while (");
1257 this->writeExpression(*w.fTest, kTopLevel_Precedence);
1258 this->write(") ");
1259 this->writeStatement(*w.fStatement);
1260}
1261
1262void MetalCodeGenerator::writeDoStatement(const DoStatement& d) {
1263 this->write("do ");
1264 this->writeStatement(*d.fStatement);
1265 this->write(" while (");
1266 this->writeExpression(*d.fTest, kTopLevel_Precedence);
1267 this->write(");");
1268}
1269
1270void MetalCodeGenerator::writeSwitchStatement(const SwitchStatement& s) {
1271 this->write("switch (");
1272 this->writeExpression(*s.fValue, kTopLevel_Precedence);
1273 this->writeLine(") {");
1274 fIndentation++;
1275 for (const auto& c : s.fCases) {
1276 if (c->fValue) {
1277 this->write("case ");
1278 this->writeExpression(*c->fValue, kTopLevel_Precedence);
1279 this->writeLine(":");
1280 } else {
1281 this->writeLine("default:");
1282 }
1283 fIndentation++;
1284 for (const auto& stmt : c->fStatements) {
1285 this->writeStatement(*stmt);
1286 this->writeLine();
1287 }
1288 fIndentation--;
1289 }
1290 fIndentation--;
1291 this->write("}");
1292}
1293
1294void MetalCodeGenerator::writeReturnStatement(const ReturnStatement& r) {
1295 this->write("return");
1296 if (r.fExpression) {
1297 this->write(" ");
1298 this->writeExpression(*r.fExpression, kTopLevel_Precedence);
1299 }
1300 this->write(";");
1301}
1302
1303void MetalCodeGenerator::writeHeader() {
1304 this->write("#include <metal_stdlib>\n");
1305 this->write("#include <simd/simd.h>\n");
1306 this->write("using namespace metal;\n");
1307}
1308
1309void MetalCodeGenerator::writeUniformStruct() {
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001310 for (const auto& e : fProgram) {
1311 if (ProgramElement::kVar_Kind == e.fKind) {
1312 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001313 if (!decls.fVars.size()) {
1314 continue;
1315 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001316 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001317 if (first.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1318 first.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001319 if (-1 == fUniformBuffer) {
1320 this->write("struct Uniforms {\n");
1321 fUniformBuffer = first.fModifiers.fLayout.fSet;
1322 if (-1 == fUniformBuffer) {
1323 fErrors.error(decls.fOffset, "Metal uniforms must have 'layout(set=...)'");
1324 }
1325 } else if (first.fModifiers.fLayout.fSet != fUniformBuffer) {
1326 if (-1 == fUniformBuffer) {
1327 fErrors.error(decls.fOffset, "Metal backend requires all uniforms to have "
1328 "the same 'layout(set=...)'");
1329 }
1330 }
1331 this->write(" ");
1332 this->writeType(first.fType);
1333 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001334 for (const auto& stmt : decls.fVars) {
1335 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001336 this->writeName(var.fVar->fName);
Ethan Nicholascc305772017-10-13 16:17:45 -04001337 }
1338 this->write(";\n");
1339 }
1340 }
1341 }
1342 if (-1 != fUniformBuffer) {
1343 this->write("};\n");
1344 }
1345}
1346
1347void MetalCodeGenerator::writeInputStruct() {
1348 this->write("struct Inputs {\n");
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001349 for (const auto& e : fProgram) {
1350 if (ProgramElement::kVar_Kind == e.fKind) {
1351 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001352 if (!decls.fVars.size()) {
1353 continue;
1354 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001355 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001356 if (first.fModifiers.fFlags & Modifiers::kIn_Flag &&
1357 -1 == first.fModifiers.fLayout.fBuiltin) {
1358 this->write(" ");
1359 this->writeType(first.fType);
1360 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001361 for (const auto& stmt : decls.fVars) {
1362 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001363 this->writeName(var.fVar->fName);
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001364 if (-1 != var.fVar->fModifiers.fLayout.fLocation) {
Timothy Liang7d637782018-06-05 09:58:07 -04001365 if (fProgram.fKind == Program::kVertex_Kind) {
1366 this->write(" [[attribute(" +
1367 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1368 } else if (fProgram.fKind == Program::kFragment_Kind) {
1369 this->write(" [[user(locn" +
1370 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1371 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001372 }
1373 }
1374 this->write(";\n");
1375 }
1376 }
1377 }
1378 this->write("};\n");
1379}
1380
1381void MetalCodeGenerator::writeOutputStruct() {
1382 this->write("struct Outputs {\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001383 if (fProgram.fKind == Program::kVertex_Kind) {
Timothy Liangb8eeb802018-07-23 16:46:16 -04001384 this->write(" float4 sk_Position [[position]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001385 } else if (fProgram.fKind == Program::kFragment_Kind) {
Timothy Liangde0be802018-08-10 13:48:08 -04001386 this->write(" float4 sk_FragColor [[color(0)]];\n");
Timothy Liang7d637782018-06-05 09:58:07 -04001387 }
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001388 for (const auto& e : fProgram) {
1389 if (ProgramElement::kVar_Kind == e.fKind) {
1390 VarDeclarations& decls = (VarDeclarations&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001391 if (!decls.fVars.size()) {
1392 continue;
1393 }
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001394 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Ethan Nicholascc305772017-10-13 16:17:45 -04001395 if (first.fModifiers.fFlags & Modifiers::kOut_Flag &&
1396 -1 == first.fModifiers.fLayout.fBuiltin) {
1397 this->write(" ");
1398 this->writeType(first.fType);
1399 this->write(" ");
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001400 for (const auto& stmt : decls.fVars) {
1401 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001402 this->writeName(var.fVar->fName);
Timothy Liang7d637782018-06-05 09:58:07 -04001403 if (fProgram.fKind == Program::kVertex_Kind) {
1404 this->write(" [[user(locn" +
1405 to_string(var.fVar->fModifiers.fLayout.fLocation) + ")]]");
1406 } else if (fProgram.fKind == Program::kFragment_Kind) {
1407 this->write(" [[color(" +
Timothy Liangde0be802018-08-10 13:48:08 -04001408 to_string(var.fVar->fModifiers.fLayout.fLocation) +")");
1409 int colorIndex = var.fVar->fModifiers.fLayout.fIndex;
1410 if (colorIndex) {
1411 this->write(", index(" + to_string(colorIndex) + ")");
1412 }
1413 this->write("]]");
Timothy Liang7d637782018-06-05 09:58:07 -04001414 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001415 }
1416 this->write(";\n");
1417 }
1418 }
Timothy Liang7d637782018-06-05 09:58:07 -04001419 }
1420 if (fProgram.fKind == Program::kVertex_Kind) {
1421 this->write(" float sk_PointSize;\n");
1422 }
1423 this->write("};\n");
1424}
1425
1426void MetalCodeGenerator::writeInterfaceBlocks() {
1427 bool wroteInterfaceBlock = false;
1428 for (const auto& e : fProgram) {
1429 if (ProgramElement::kInterfaceBlock_Kind == e.fKind) {
1430 this->writeInterfaceBlock((InterfaceBlock&) e);
1431 wroteInterfaceBlock = true;
1432 }
1433 }
Jim Van Verth3d482992019-02-07 10:48:05 -05001434 if (!wroteInterfaceBlock && fProgram.fInputs.fRTHeight) {
Timothy Liang7d637782018-06-05 09:58:07 -04001435 this->writeLine("struct sksl_synthetic_uniforms {");
1436 this->writeLine(" float u_skRTHeight;");
1437 this->writeLine("};");
1438 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001439}
1440
Timothy Liangee84fe12018-05-18 14:38:19 -04001441void MetalCodeGenerator::writeGlobalStruct() {
1442 bool wroteStructDecl = false;
Timothy Liang7d637782018-06-05 09:58:07 -04001443 for (const auto& intf : fInterfaceBlockNameMap) {
1444 if (!wroteStructDecl) {
1445 this->write("struct Globals {\n");
1446 wroteStructDecl = true;
1447 }
1448 fNeedsGlobalStructInit = true;
1449 const auto& intfType = intf.first;
1450 const auto& intfName = intf.second;
1451 this->write(" constant ");
1452 this->write(intfType->fTypeName);
1453 this->write("* ");
Timothy Liang651286f2018-06-07 09:55:33 -04001454 this->writeName(intfName);
Timothy Liang7d637782018-06-05 09:58:07 -04001455 this->write(";\n");
1456 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001457 for (const auto& e : fProgram) {
1458 if (ProgramElement::kVar_Kind == e.fKind) {
1459 VarDeclarations& decls = (VarDeclarations&) e;
1460 if (!decls.fVars.size()) {
1461 continue;
1462 }
1463 const Variable& first = *((VarDeclaration&) *decls.fVars[0]).fVar;
Timothy Lianga06f2152018-05-24 15:33:31 -04001464 if ((!first.fModifiers.fFlags && -1 == first.fModifiers.fLayout.fBuiltin) ||
1465 first.fType.kind() == Type::kSampler_Kind) {
Timothy Liangee84fe12018-05-18 14:38:19 -04001466 if (!wroteStructDecl) {
1467 this->write("struct Globals {\n");
1468 wroteStructDecl = true;
1469 }
1470 fNeedsGlobalStructInit = true;
1471 this->write(" ");
1472 this->writeType(first.fType);
1473 this->write(" ");
1474 for (const auto& stmt : decls.fVars) {
1475 VarDeclaration& var = (VarDeclaration&) *stmt;
Timothy Liang651286f2018-06-07 09:55:33 -04001476 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001477 if (var.fVar->fType.kind() == Type::kSampler_Kind) {
1478 fTextures.push_back(var.fVar);
1479 this->write(";\n");
1480 this->write(" sampler ");
Timothy Liang651286f2018-06-07 09:55:33 -04001481 this->writeName(var.fVar->fName);
Timothy Lianga06f2152018-05-24 15:33:31 -04001482 this->write(SAMPLER_SUFFIX);
1483 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001484 if (var.fValue) {
1485 fInitNonConstGlobalVars.push_back(&var);
1486 }
1487 }
1488 this->write(";\n");
1489 }
1490 }
1491 }
Timothy Liangee84fe12018-05-18 14:38:19 -04001492 if (wroteStructDecl) {
1493 this->write("};\n");
1494 }
1495}
1496
Ethan Nicholascc305772017-10-13 16:17:45 -04001497void MetalCodeGenerator::writeProgramElement(const ProgramElement& e) {
1498 switch (e.fKind) {
1499 case ProgramElement::kExtension_Kind:
1500 break;
1501 case ProgramElement::kVar_Kind: {
1502 VarDeclarations& decl = (VarDeclarations&) e;
1503 if (decl.fVars.size() > 0) {
Ethan Nicholas82a62d22017-11-07 14:42:10 +00001504 int builtin = ((VarDeclaration&) *decl.fVars[0]).fVar->fModifiers.fLayout.fBuiltin;
Ethan Nicholascc305772017-10-13 16:17:45 -04001505 if (-1 == builtin) {
1506 // normal var
1507 this->writeVarDeclarations(decl, true);
1508 this->writeLine();
1509 } else if (SK_FRAGCOLOR_BUILTIN == builtin) {
1510 // ignore
1511 }
1512 }
1513 break;
1514 }
1515 case ProgramElement::kInterfaceBlock_Kind:
Timothy Liang7d637782018-06-05 09:58:07 -04001516 // handled in writeInterfaceBlocks, do nothing
Ethan Nicholascc305772017-10-13 16:17:45 -04001517 break;
1518 case ProgramElement::kFunction_Kind:
1519 this->writeFunction((FunctionDefinition&) e);
1520 break;
1521 case ProgramElement::kModifiers_Kind:
1522 this->writeModifiers(((ModifiersDeclaration&) e).fModifiers, true);
1523 this->writeLine(";");
1524 break;
1525 default:
1526 printf("%s\n", e.description().c_str());
1527 ABORT("unsupported program element");
1528 }
1529}
1530
1531MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Expression& e) {
1532 switch (e.fKind) {
1533 case Expression::kFunctionCall_Kind: {
1534 const FunctionCall& f = (const FunctionCall&) e;
1535 Requirements result = this->requirements(f.fFunction);
1536 for (const auto& e : f.fArguments) {
1537 result |= this->requirements(*e);
1538 }
1539 return result;
1540 }
1541 case Expression::kConstructor_Kind: {
1542 const Constructor& c = (const Constructor&) e;
1543 Requirements result = kNo_Requirements;
1544 for (const auto& e : c.fArguments) {
1545 result |= this->requirements(*e);
1546 }
1547 return result;
1548 }
Timothy Liang7d637782018-06-05 09:58:07 -04001549 case Expression::kFieldAccess_Kind: {
1550 const FieldAccess& f = (const FieldAccess&) e;
1551 if (FieldAccess::kAnonymousInterfaceBlock_OwnerKind == f.fOwnerKind) {
1552 return kGlobals_Requirement;
1553 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001554 return this->requirements(*((const FieldAccess&) e).fBase);
Timothy Liang7d637782018-06-05 09:58:07 -04001555 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001556 case Expression::kSwizzle_Kind:
1557 return this->requirements(*((const Swizzle&) e).fBase);
1558 case Expression::kBinary_Kind: {
1559 const BinaryExpression& b = (const BinaryExpression&) e;
1560 return this->requirements(*b.fLeft) | this->requirements(*b.fRight);
1561 }
1562 case Expression::kIndex_Kind: {
1563 const IndexExpression& idx = (const IndexExpression&) e;
1564 return this->requirements(*idx.fBase) | this->requirements(*idx.fIndex);
1565 }
1566 case Expression::kPrefix_Kind:
1567 return this->requirements(*((const PrefixExpression&) e).fOperand);
1568 case Expression::kPostfix_Kind:
1569 return this->requirements(*((const PostfixExpression&) e).fOperand);
1570 case Expression::kTernary_Kind: {
1571 const TernaryExpression& t = (const TernaryExpression&) e;
1572 return this->requirements(*t.fTest) | this->requirements(*t.fIfTrue) |
1573 this->requirements(*t.fIfFalse);
1574 }
1575 case Expression::kVariableReference_Kind: {
1576 const VariableReference& v = (const VariableReference&) e;
1577 Requirements result = kNo_Requirements;
1578 if (v.fVariable.fModifiers.fLayout.fBuiltin == SK_FRAGCOORD_BUILTIN) {
Ethan Nicholasc6dce5a2019-07-24 16:51:36 -04001579 result = kGlobals_Requirement | kFragCoord_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001580 } else if (Variable::kGlobal_Storage == v.fVariable.fStorage) {
1581 if (v.fVariable.fModifiers.fFlags & Modifiers::kIn_Flag) {
1582 result = kInputs_Requirement;
1583 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kOut_Flag) {
1584 result = kOutputs_Requirement;
Timothy Lianga06f2152018-05-24 15:33:31 -04001585 } else if (v.fVariable.fModifiers.fFlags & Modifiers::kUniform_Flag &&
1586 v.fVariable.fType.kind() != Type::kSampler_Kind) {
Ethan Nicholascc305772017-10-13 16:17:45 -04001587 result = kUniforms_Requirement;
Timothy Liangee84fe12018-05-18 14:38:19 -04001588 } else {
1589 result = kGlobals_Requirement;
Ethan Nicholascc305772017-10-13 16:17:45 -04001590 }
1591 }
1592 return result;
1593 }
1594 default:
1595 return kNo_Requirements;
1596 }
1597}
1598
1599MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const Statement& s) {
1600 switch (s.fKind) {
1601 case Statement::kBlock_Kind: {
1602 Requirements result = kNo_Requirements;
1603 for (const auto& child : ((const Block&) s).fStatements) {
1604 result |= this->requirements(*child);
1605 }
1606 return result;
1607 }
Timothy Liang7d637782018-06-05 09:58:07 -04001608 case Statement::kVarDeclaration_Kind: {
1609 Requirements result = kNo_Requirements;
1610 const VarDeclaration& var = (const VarDeclaration&) s;
1611 if (var.fValue) {
1612 result = this->requirements(*var.fValue);
1613 }
1614 return result;
1615 }
1616 case Statement::kVarDeclarations_Kind: {
1617 Requirements result = kNo_Requirements;
1618 const VarDeclarations& decls = *((const VarDeclarationsStatement&) s).fDeclaration;
1619 for (const auto& stmt : decls.fVars) {
1620 result |= this->requirements(*stmt);
1621 }
1622 return result;
1623 }
Ethan Nicholascc305772017-10-13 16:17:45 -04001624 case Statement::kExpression_Kind:
1625 return this->requirements(*((const ExpressionStatement&) s).fExpression);
1626 case Statement::kReturn_Kind: {
1627 const ReturnStatement& r = (const ReturnStatement&) s;
1628 if (r.fExpression) {
1629 return this->requirements(*r.fExpression);
1630 }
1631 return kNo_Requirements;
1632 }
1633 case Statement::kIf_Kind: {
1634 const IfStatement& i = (const IfStatement&) s;
1635 return this->requirements(*i.fTest) |
1636 this->requirements(*i.fIfTrue) |
Ethan Nicholasf931e402019-07-26 15:40:33 -04001637 (i.fIfFalse ? this->requirements(*i.fIfFalse) : 0);
Ethan Nicholascc305772017-10-13 16:17:45 -04001638 }
1639 case Statement::kFor_Kind: {
1640 const ForStatement& f = (const ForStatement&) s;
1641 return this->requirements(*f.fInitializer) |
1642 this->requirements(*f.fTest) |
1643 this->requirements(*f.fNext) |
1644 this->requirements(*f.fStatement);
1645 }
1646 case Statement::kWhile_Kind: {
1647 const WhileStatement& w = (const WhileStatement&) s;
1648 return this->requirements(*w.fTest) |
1649 this->requirements(*w.fStatement);
1650 }
1651 case Statement::kDo_Kind: {
1652 const DoStatement& d = (const DoStatement&) s;
1653 return this->requirements(*d.fTest) |
1654 this->requirements(*d.fStatement);
1655 }
1656 case Statement::kSwitch_Kind: {
1657 const SwitchStatement& sw = (const SwitchStatement&) s;
1658 Requirements result = this->requirements(*sw.fValue);
1659 for (const auto& c : sw.fCases) {
1660 for (const auto& st : c->fStatements) {
1661 result |= this->requirements(*st);
1662 }
1663 }
1664 return result;
1665 }
1666 default:
1667 return kNo_Requirements;
1668 }
1669}
1670
1671MetalCodeGenerator::Requirements MetalCodeGenerator::requirements(const FunctionDeclaration& f) {
1672 if (f.fBuiltin) {
1673 return kNo_Requirements;
1674 }
1675 auto found = fRequirements.find(&f);
1676 if (found == fRequirements.end()) {
Ethan Nicholas65a8f562019-04-19 14:00:26 -04001677 fRequirements[&f] = kNo_Requirements;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001678 for (const auto& e : fProgram) {
1679 if (ProgramElement::kFunction_Kind == e.fKind) {
1680 const FunctionDefinition& def = (const FunctionDefinition&) e;
Ethan Nicholascc305772017-10-13 16:17:45 -04001681 if (&def.fDeclaration == &f) {
1682 Requirements reqs = this->requirements(*def.fBody);
1683 fRequirements[&f] = reqs;
1684 return reqs;
1685 }
1686 }
1687 }
1688 }
1689 return found->second;
1690}
1691
Timothy Liangb8eeb802018-07-23 16:46:16 -04001692bool MetalCodeGenerator::generateCode() {
Ethan Nicholascc305772017-10-13 16:17:45 -04001693 OutputStream* rawOut = fOut;
1694 fOut = &fHeader;
Timothy Liangb8eeb802018-07-23 16:46:16 -04001695#ifdef SK_MOLTENVK
1696 fOut->write((const char*) &MVKMagicNum, sizeof(MVKMagicNum));
1697#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001698 fProgramKind = fProgram.fKind;
1699 this->writeHeader();
1700 this->writeUniformStruct();
1701 this->writeInputStruct();
Timothy Liang7d637782018-06-05 09:58:07 -04001702 this->writeOutputStruct();
1703 this->writeInterfaceBlocks();
Timothy Liangee84fe12018-05-18 14:38:19 -04001704 this->writeGlobalStruct();
Ethan Nicholascc305772017-10-13 16:17:45 -04001705 StringStream body;
1706 fOut = &body;
Ethan Nicholas3c6ae622018-04-24 13:06:09 -04001707 for (const auto& e : fProgram) {
1708 this->writeProgramElement(e);
Ethan Nicholascc305772017-10-13 16:17:45 -04001709 }
1710 fOut = rawOut;
1711
1712 write_stringstream(fHeader, *rawOut);
Chris Daltondba7aab2018-11-15 10:57:49 -05001713 write_stringstream(fExtraFunctions, *rawOut);
Ethan Nicholascc305772017-10-13 16:17:45 -04001714 write_stringstream(body, *rawOut);
Timothy Liangb8eeb802018-07-23 16:46:16 -04001715#ifdef SK_MOLTENVK
1716 this->write("\0");
1717#endif
Ethan Nicholascc305772017-10-13 16:17:45 -04001718 return true;
Ethan Nicholascc305772017-10-13 16:17:45 -04001719}
1720
1721}