1/*
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
8#ifndef SKSL_METALCODEGENERATOR
9#define SKSL_METALCODEGENERATOR
10
11#include <stack>
12#include <tuple>
13#include <unordered_map>
14#include <unordered_set>
15
16#include "src/sksl/SkSLCodeGenerator.h"
17#include "src/sksl/SkSLMemoryLayout.h"
18#include "src/sksl/SkSLStringStream.h"
19#include "src/sksl/ir/SkSLBinaryExpression.h"
20#include "src/sksl/ir/SkSLBoolLiteral.h"
21#include "src/sksl/ir/SkSLConstructor.h"
22#include "src/sksl/ir/SkSLDoStatement.h"
23#include "src/sksl/ir/SkSLExtension.h"
24#include "src/sksl/ir/SkSLFieldAccess.h"
25#include "src/sksl/ir/SkSLFloatLiteral.h"
26#include "src/sksl/ir/SkSLForStatement.h"
27#include "src/sksl/ir/SkSLFunctionCall.h"
28#include "src/sksl/ir/SkSLFunctionDeclaration.h"
29#include "src/sksl/ir/SkSLFunctionDefinition.h"
30#include "src/sksl/ir/SkSLIfStatement.h"
31#include "src/sksl/ir/SkSLIndexExpression.h"
32#include "src/sksl/ir/SkSLIntLiteral.h"
33#include "src/sksl/ir/SkSLInterfaceBlock.h"
34#include "src/sksl/ir/SkSLPostfixExpression.h"
35#include "src/sksl/ir/SkSLPrefixExpression.h"
36#include "src/sksl/ir/SkSLProgramElement.h"
37#include "src/sksl/ir/SkSLReturnStatement.h"
38#include "src/sksl/ir/SkSLSetting.h"
39#include "src/sksl/ir/SkSLStatement.h"
40#include "src/sksl/ir/SkSLSwitchStatement.h"
41#include "src/sksl/ir/SkSLSwizzle.h"
42#include "src/sksl/ir/SkSLTernaryExpression.h"
43#include "src/sksl/ir/SkSLVarDeclarations.h"
44#include "src/sksl/ir/SkSLVarDeclarationsStatement.h"
45#include "src/sksl/ir/SkSLVariableReference.h"
46#include "src/sksl/ir/SkSLWhileStatement.h"
47
48namespace SkSL {
49
50#define kLast_Capability SpvCapabilityMultiViewport
51
52/**
53 * Converts a Program into Metal code.
54 */
55class MetalCodeGenerator : public CodeGenerator {
56public:
57 static constexpr const char* SAMPLER_SUFFIX = "Smplr";
58 static constexpr const char* PACKED_PREFIX = "packed_";
59
60 enum Precedence {
61 kParentheses_Precedence = 1,
62 kPostfix_Precedence = 2,
63 kPrefix_Precedence = 3,
64 kMultiplicative_Precedence = 4,
65 kAdditive_Precedence = 5,
66 kShift_Precedence = 6,
67 kRelational_Precedence = 7,
68 kEquality_Precedence = 8,
69 kBitwiseAnd_Precedence = 9,
70 kBitwiseXor_Precedence = 10,
71 kBitwiseOr_Precedence = 11,
72 kLogicalAnd_Precedence = 12,
73 kLogicalXor_Precedence = 13,
74 kLogicalOr_Precedence = 14,
75 kTernary_Precedence = 15,
76 kAssignment_Precedence = 16,
77 kSequence_Precedence = 17,
78 kTopLevel_Precedence = kSequence_Precedence
79 };
80
81 MetalCodeGenerator(const Context* context, const Program* program, ErrorReporter* errors,
82 OutputStream* out)
83 : INHERITED(program, errors, out)
84 , fReservedWords({"atan2", "rsqrt", "dfdx", "dfdy", "vertex", "fragment"})
85 , fLineEnding("\n")
86 , fContext(*context) {
87 this->setupIntrinsics();
88 }
89
90 bool generateCode() override;
91
92protected:
93 typedef int Requirements;
94 static constexpr Requirements kNo_Requirements = 0;
95 static constexpr Requirements kInputs_Requirement = 1 << 0;
96 static constexpr Requirements kOutputs_Requirement = 1 << 1;
97 static constexpr Requirements kUniforms_Requirement = 1 << 2;
98 static constexpr Requirements kGlobals_Requirement = 1 << 3;
99 static constexpr Requirements kFragCoord_Requirement = 1 << 4;
100
101 enum IntrinsicKind {
102 kSpecial_IntrinsicKind,
103 kMetal_IntrinsicKind,
104 };
105
106 enum SpecialIntrinsic {
107 kTexture_SpecialIntrinsic,
108 kMod_SpecialIntrinsic,
109 };
110
111 enum MetalIntrinsic {
112 kEqual_MetalIntrinsic,
113 kNotEqual_MetalIntrinsic,
114 kLessThan_MetalIntrinsic,
115 kLessThanEqual_MetalIntrinsic,
116 kGreaterThan_MetalIntrinsic,
117 kGreaterThanEqual_MetalIntrinsic,
118 };
119
120 class GlobalStructVisitor;
121 void visitGlobalStruct(GlobalStructVisitor* visitor);
122
123 void setupIntrinsics();
124
125 void write(const char* s);
126
127 void writeLine();
128
129 void writeLine(const char* s);
130
131 void write(const String& s);
132
133 void writeLine(const String& s);
134
135 void writeHeader();
136
137 void writeUniformStruct();
138
139 void writeInputStruct();
140
141 void writeOutputStruct();
142
143 void writeInterfaceBlocks();
144
145 void writeFields(const std::vector<Type::Field>& fields, int parentOffset,
146 const InterfaceBlock* parentIntf = nullptr);
147
148 int size(const Type* type, bool isPacked) const;
149
150 int alignment(const Type* type, bool isPacked) const;
151
152 void writeGlobalStruct();
153 void writeGlobalInit();
154
155 void writePrecisionModifier();
156
157 String typeName(const Type& type);
158
159 void writeType(const Type& type);
160
161 void writeExtension(const Extension& ext);
162
163 void writeInterfaceBlock(const InterfaceBlock& intf);
164
165 void writeFunctionStart(const FunctionDeclaration& f);
166
167 void writeFunctionDeclaration(const FunctionDeclaration& f);
168
169 void writeFunction(const FunctionDefinition& f);
170
171 void writeLayout(const Layout& layout);
172
173 void writeModifiers(const Modifiers& modifiers, bool globalContext);
174
175 void writeVarInitializer(const Variable& var, const Expression& value);
176
177 void writeName(const String& name);
178
179 void writeVarDeclarations(const VarDeclarations& decl, bool global);
180
181 void writeFragCoord();
182
183 void writeVariableReference(const VariableReference& ref);
184
185 void writeExpression(const Expression& expr, Precedence parentPrecedence);
186
187 void writeIntrinsicCall(const FunctionCall& c);
188
189 void writeMinAbsHack(Expression& absExpr, Expression& otherExpr);
190
191 void writeFunctionCall(const FunctionCall& c);
192
193 void writeInverseHack(const Expression& mat);
194
195 bool matrixConstructHelperIsNeeded(const Constructor& c);
196 String getMatrixConstructHelper(const Constructor& c);
197 void assembleMatrixFromMatrix(const Type& sourceMatrix, int rows, int columns);
198 void assembleMatrixFromExpressions(const std::vector<std::unique_ptr<Expression>>& args,
199 int rows, int columns);
200
201 void writeMatrixTimesEqualHelper(const Type& left, const Type& right, const Type& result);
202
203 void writeSpecialIntrinsic(const FunctionCall& c, SpecialIntrinsic kind);
204
205 bool canCoerce(const Type& t1, const Type& t2);
206
207 void writeConstructor(const Constructor& c, Precedence parentPrecedence);
208
209 void writeFieldAccess(const FieldAccess& f);
210
211 void writeSwizzle(const Swizzle& swizzle);
212
213 static Precedence GetBinaryPrecedence(Token::Kind op);
214
215 void writeBinaryExpression(const BinaryExpression& b, Precedence parentPrecedence);
216
217 void writeTernaryExpression(const TernaryExpression& t, Precedence parentPrecedence);
218
219 void writeIndexExpression(const IndexExpression& expr);
220
221 void writePrefixExpression(const PrefixExpression& p, Precedence parentPrecedence);
222
223 void writePostfixExpression(const PostfixExpression& p, Precedence parentPrecedence);
224
225 void writeBoolLiteral(const BoolLiteral& b);
226
227 void writeIntLiteral(const IntLiteral& i);
228
229 void writeFloatLiteral(const FloatLiteral& f);
230
231 void writeSetting(const Setting& s);
232
233 void writeStatement(const Statement& s);
234
235 void writeStatements(const std::vector<std::unique_ptr<Statement>>& statements);
236
237 void writeBlock(const Block& b);
238
239 void writeIfStatement(const IfStatement& stmt);
240
241 void writeForStatement(const ForStatement& f);
242
243 void writeWhileStatement(const WhileStatement& w);
244
245 void writeDoStatement(const DoStatement& d);
246
247 void writeSwitchStatement(const SwitchStatement& s);
248
249 void writeReturnStatement(const ReturnStatement& r);
250
251 void writeProgramElement(const ProgramElement& e);
252
253 Requirements requirements(const FunctionDeclaration& f);
254
255 Requirements requirements(const Expression* e);
256
257 Requirements requirements(const Statement* s);
258
259 typedef std::pair<IntrinsicKind, int32_t> Intrinsic;
260 std::unordered_map<String, Intrinsic> fIntrinsicMap;
261 std::unordered_set<String> fReservedWords;
262 std::unordered_map<const Type::Field*, const InterfaceBlock*> fInterfaceBlockMap;
263 std::unordered_map<const InterfaceBlock*, String> fInterfaceBlockNameMap;
264 int fAnonInterfaceCount = 0;
265 int fPaddingCount = 0;
266 const char* fLineEnding;
267 const Context& fContext;
268 StringStream fHeader;
269 String fFunctionHeader;
270 StringStream fExtraFunctions;
271 Program::Kind fProgramKind;
272 int fVarCount = 0;
273 int fIndentation = 0;
274 bool fAtLineStart = false;
275 // Keeps track of which struct types we have written. Given that we are unlikely to ever write
276 // more than one or two structs per shader, a simple linear search will be faster than anything
277 // fancier.
278 std::vector<const Type*> fWrittenStructs;
279 std::set<String> fWrittenIntrinsics;
280 // true if we have run into usages of dFdx / dFdy
281 bool fFoundDerivatives = false;
282 std::unordered_map<const FunctionDeclaration*, Requirements> fRequirements;
283 bool fSetupFragPositionGlobal = false;
284 bool fSetupFragPositionLocal = false;
285 std::unordered_set<String> fHelpers;
286 int fUniformBuffer = -1;
287 String fRTHeightName;
288
289 typedef CodeGenerator INHERITED;
290};
291
292} // namespace SkSL
293
294#endif
295