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#include "src/sksl/SkSLHCodeGenerator.h"
9
10#include "include/private/SkSLSampleUsage.h"
11#include "src/sksl/SkSLAnalysis.h"
12#include "src/sksl/SkSLParser.h"
13#include "src/sksl/SkSLUtil.h"
14#include "src/sksl/ir/SkSLEnum.h"
15#include "src/sksl/ir/SkSLFunctionDeclaration.h"
16#include "src/sksl/ir/SkSLFunctionDefinition.h"
17#include "src/sksl/ir/SkSLSection.h"
18#include "src/sksl/ir/SkSLVarDeclarations.h"
19
20#include <set>
21
22namespace SkSL {
23
24HCodeGenerator::HCodeGenerator(const Context* context, const Program* program,
25 ErrorReporter* errors, String name, OutputStream* out)
26: INHERITED(program, errors, out)
27, fContext(*context)
28, fName(std::move(name))
29, fFullName(String::printf("Gr%s", fName.c_str()))
30, fSectionAndParameterHelper(program, *errors) {}
31
32String HCodeGenerator::ParameterType(const Context& context, const Type& type,
33 const Layout& layout) {
34 Layout::CType ctype = ParameterCType(context, type, layout);
35 if (ctype != Layout::CType::kDefault) {
36 return Layout::CTypeToStr(ctype);
37 }
38 return type.name();
39}
40
41Layout::CType HCodeGenerator::ParameterCType(const Context& context, const Type& type,
42 const Layout& layout) {
43 if (layout.fCType != Layout::CType::kDefault) {
44 return layout.fCType;
45 }
46 if (type.kind() == Type::kNullable_Kind) {
47 return ParameterCType(context, type.componentType(), layout);
48 } else if (type == *context.fFloat_Type || type == *context.fHalf_Type) {
49 return Layout::CType::kFloat;
50 } else if (type == *context.fInt_Type ||
51 type == *context.fShort_Type ||
52 type == *context.fByte_Type) {
53 return Layout::CType::kInt32;
54 } else if (type == *context.fFloat2_Type || type == *context.fHalf2_Type) {
55 return Layout::CType::kSkPoint;
56 } else if (type == *context.fInt2_Type ||
57 type == *context.fShort2_Type ||
58 type == *context.fByte2_Type) {
59 return Layout::CType::kSkIPoint;
60 } else if (type == *context.fInt4_Type ||
61 type == *context.fShort4_Type ||
62 type == *context.fByte4_Type) {
63 return Layout::CType::kSkIRect;
64 } else if (type == *context.fFloat4_Type || type == *context.fHalf4_Type) {
65 return Layout::CType::kSkRect;
66 } else if (type == *context.fFloat3x3_Type || type == *context.fHalf3x3_Type) {
67 return Layout::CType::kSkMatrix;
68 } else if (type == *context.fFloat4x4_Type || type == *context.fHalf4x4_Type) {
69 return Layout::CType::kSkM44;
70 } else if (type.kind() == Type::kSampler_Kind) {
71 return Layout::CType::kGrSurfaceProxyView;
72 } else if (type == *context.fFragmentProcessor_Type) {
73 return Layout::CType::kGrFragmentProcessor;
74 }
75 return Layout::CType::kDefault;
76}
77
78String HCodeGenerator::FieldType(const Context& context, const Type& type,
79 const Layout& layout) {
80 if (type.kind() == Type::kSampler_Kind) {
81 return "TextureSampler";
82 } else if (type == *context.fFragmentProcessor_Type) {
83 // we don't store fragment processors in fields, they get registered via
84 // registerChildProcessor instead
85 SkASSERT(false);
86 return "<error>";
87 }
88 return ParameterType(context, type, layout);
89}
90
91String HCodeGenerator::AccessType(const Context& context, const Type& type,
92 const Layout& layout) {
93 static const std::set<String> primitiveTypes = { "int32_t", "float", "bool", "SkPMColor" };
94
95 String fieldType = FieldType(context, type, layout);
96 bool isPrimitive = primitiveTypes.find(fieldType) != primitiveTypes.end();
97 if (isPrimitive) {
98 return fieldType;
99 } else {
100 return String::printf("const %s&", fieldType.c_str());
101 }
102}
103
104void HCodeGenerator::writef(const char* s, va_list va) {
105 static constexpr int BUFFER_SIZE = 1024;
106 va_list copy;
107 va_copy(copy, va);
108 char buffer[BUFFER_SIZE];
109 int length = vsnprintf(buffer, BUFFER_SIZE, s, va);
110 if (length < BUFFER_SIZE) {
111 fOut->write(buffer, length);
112 } else {
113 std::unique_ptr<char[]> heap(new char[length + 1]);
114 vsprintf(heap.get(), s, copy);
115 fOut->write(heap.get(), length);
116 }
117 va_end(copy);
118}
119
120void HCodeGenerator::writef(const char* s, ...) {
121 va_list va;
122 va_start(va, s);
123 this->writef(s, va);
124 va_end(va);
125}
126
127bool HCodeGenerator::writeSection(const char* name, const char* prefix) {
128 const Section* s = fSectionAndParameterHelper.getSection(name);
129 if (s) {
130 this->writef("%s%s", prefix, s->fText.c_str());
131 return true;
132 }
133 return false;
134}
135
136void HCodeGenerator::writeExtraConstructorParams(const char* separator) {
137 // super-simple parse, just assume the last token before a comma is the name of a parameter
138 // (which is true as long as there are no multi-parameter template types involved). Will replace
139 // this with something more robust if the need arises.
140 const Section* section = fSectionAndParameterHelper.getSection(kConstructorParamsSection);
141 if (section) {
142 const char* s = section->fText.c_str();
143 #define BUFFER_SIZE 64
144 char lastIdentifier[BUFFER_SIZE];
145 int lastIdentifierLength = 0;
146 bool foundBreak = false;
147 while (*s) {
148 char c = *s;
149 ++s;
150 if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') ||
151 c == '_') {
152 if (foundBreak) {
153 lastIdentifierLength = 0;
154 foundBreak = false;
155 }
156 SkASSERT(lastIdentifierLength < BUFFER_SIZE);
157 lastIdentifier[lastIdentifierLength] = c;
158 ++lastIdentifierLength;
159 } else {
160 foundBreak = true;
161 if (c == ',') {
162 SkASSERT(lastIdentifierLength < BUFFER_SIZE);
163 lastIdentifier[lastIdentifierLength] = 0;
164 this->writef("%s%s", separator, lastIdentifier);
165 separator = ", ";
166 } else if (c != ' ' && c != '\t' && c != '\n' && c != '\r') {
167 lastIdentifierLength = 0;
168 }
169 }
170 }
171 if (lastIdentifierLength) {
172 SkASSERT(lastIdentifierLength < BUFFER_SIZE);
173 lastIdentifier[lastIdentifierLength] = 0;
174 this->writef("%s%s", separator, lastIdentifier);
175 }
176 }
177}
178
179void HCodeGenerator::writeMake() {
180 const char* separator;
181 if (!this->writeSection(kMakeSection)) {
182 this->writef(" static std::unique_ptr<GrFragmentProcessor> Make(");
183 separator = "";
184 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
185 this->writef("%s%s %s", separator, ParameterType(fContext, param->fType,
186 param->fModifiers.fLayout).c_str(),
187 String(param->fName).c_str());
188 separator = ", ";
189 }
190 this->writeSection(kConstructorParamsSection, separator);
191 this->writef(") {\n"
192 " return std::unique_ptr<GrFragmentProcessor>(new %s(",
193 fFullName.c_str());
194 separator = "";
195 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
196 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type ||
197 param->fType.nonnullable().kind() == Type::kSampler_Kind) {
198 this->writef("%sstd::move(%s)", separator, String(param->fName).c_str());
199 } else {
200 this->writef("%s%s", separator, String(param->fName).c_str());
201 }
202 separator = ", ";
203 }
204 this->writeExtraConstructorParams(separator);
205 this->writef("));\n"
206 " }\n");
207 }
208}
209
210void HCodeGenerator::failOnSection(const char* section, const char* msg) {
211 std::vector<const Section*> s = fSectionAndParameterHelper.getSections(section);
212 if (s.size()) {
213 fErrors.error(s[0]->fOffset, String("@") + section + " " + msg);
214 }
215}
216
217void HCodeGenerator::writeConstructor() {
218 if (this->writeSection(kConstructorSection)) {
219 const char* msg = "may not be present when constructor is overridden";
220 this->failOnSection(kConstructorCodeSection, msg);
221 this->failOnSection(kConstructorParamsSection, msg);
222 this->failOnSection(kInitializersSection, msg);
223 this->failOnSection(kOptimizationFlagsSection, msg);
224 return;
225 }
226 this->writef(" %s(", fFullName.c_str());
227 const char* separator = "";
228 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
229 this->writef("%s%s %s", separator, ParameterType(fContext, param->fType,
230 param->fModifiers.fLayout).c_str(),
231 String(param->fName).c_str());
232 separator = ", ";
233 }
234 this->writeSection(kConstructorParamsSection, separator);
235 this->writef(")\n"
236 " : INHERITED(k%s_ClassID", fFullName.c_str());
237 if (!this->writeSection(kOptimizationFlagsSection, ", (OptimizationFlags) ")) {
238 this->writef(", kNone_OptimizationFlags");
239 }
240 this->writef(")");
241 this->writeSection(kInitializersSection, "\n , ");
242 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
243 String nameString(param->fName);
244 const char* name = nameString.c_str();
245 const Type& type = param->fType.nonnullable();
246 if (type.kind() == Type::kSampler_Kind) {
247 this->writef("\n , %s(std::move(%s)", FieldName(name).c_str(), name);
248 for (const Section* s : fSectionAndParameterHelper.getSections(
249 kSamplerParamsSection)) {
250 if (s->fArgument == name) {
251 this->writef(", %s", s->fText.c_str());
252 }
253 }
254 this->writef(")");
255 } else if (type == *fContext.fFragmentProcessor_Type) {
256 // do nothing
257 } else {
258 this->writef("\n , %s(%s)", FieldName(name).c_str(), name);
259 }
260 }
261 this->writef(" {\n");
262 this->writeSection(kConstructorCodeSection);
263
264 if (Analysis::ReferencesSampleCoords(fProgram)) {
265 this->writef(" this->setUsesSampleCoordsDirectly();\n");
266 }
267
268 int samplerCount = 0;
269 for (const Variable* param : fSectionAndParameterHelper.getParameters()) {
270 if (param->fType.kind() == Type::kSampler_Kind) {
271 ++samplerCount;
272 } else if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
273 if (param->fType.kind() != Type::kNullable_Kind) {
274 this->writef(" SkASSERT(%s);", String(param->fName).c_str());
275 }
276
277 SampleUsage usage = Analysis::GetSampleUsage(fProgram, *param);
278
279 std::string perspExpression;
280 if (usage.hasUniformMatrix()) {
281 for (const Variable* p : fSectionAndParameterHelper.getParameters()) {
282 if ((p->fModifiers.fFlags & Modifiers::kIn_Flag) &&
283 usage.fExpression == String(p->fName)) {
284 perspExpression = usage.fExpression + ".hasPerspective()";
285 break;
286 }
287 }
288 }
289 std::string usageArg = usage.constructor(std::move(perspExpression));
290
291 this->writef(" this->registerChild(std::move(%s), %s);",
292 String(param->fName).c_str(),
293 usageArg.c_str());
294 }
295 }
296 if (samplerCount) {
297 this->writef(" this->setTextureSamplerCnt(%d);", samplerCount);
298 }
299 this->writef(" }\n");
300}
301
302void HCodeGenerator::writeFields() {
303 this->writeSection(kFieldsSection);
304 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
305 String name = FieldName(String(param->fName).c_str());
306 if (param->fType.nonnullable() == *fContext.fFragmentProcessor_Type) {
307 // Don't need to write any fields, FPs are held as children
308 } else {
309 this->writef(" %s %s;\n", FieldType(fContext, param->fType,
310 param->fModifiers.fLayout).c_str(),
311 name.c_str());
312 }
313 }
314}
315
316String HCodeGenerator::GetHeader(const Program& program, ErrorReporter& errors) {
317 SymbolTable types(&errors);
318 Parser parser(program.fSource->c_str(), program.fSource->length(), types, errors);
319 for (;;) {
320 Token header = parser.nextRawToken();
321 switch (header.fKind) {
322 case Token::Kind::TK_WHITESPACE:
323 break;
324 case Token::Kind::TK_BLOCK_COMMENT:
325 return String(program.fSource->c_str() + header.fOffset, header.fLength);
326 default:
327 return "";
328 }
329 }
330}
331
332bool HCodeGenerator::generateCode() {
333 this->writef("%s\n", GetHeader(fProgram, fErrors).c_str());
334 this->writef(kFragmentProcessorHeader, fFullName.c_str());
335 this->writef("#ifndef %s_DEFINED\n"
336 "#define %s_DEFINED\n"
337 "\n"
338 "#include \"include/core/SkM44.h\"\n"
339 "#include \"include/core/SkTypes.h\"\n"
340 "\n",
341 fFullName.c_str(),
342 fFullName.c_str());
343 this->writeSection(kHeaderSection);
344 this->writef("\n"
345 "#include \"src/gpu/GrFragmentProcessor.h\"\n"
346 "\n"
347 "class %s : public GrFragmentProcessor {\n"
348 "public:\n",
349 fFullName.c_str());
350 for (const auto& p : fProgram) {
351 if (ProgramElement::kEnum_Kind == p.fKind && !((Enum&) p).fBuiltin) {
352 this->writef("%s\n", ((Enum&) p).code().c_str());
353 }
354 }
355 this->writeSection(kClassSection);
356 this->writeMake();
357 this->writef(" %s(const %s& src);\n"
358 " std::unique_ptr<GrFragmentProcessor> clone() const override;\n"
359 " const char* name() const override { return \"%s\"; }\n",
360 fFullName.c_str(), fFullName.c_str(), fName.c_str());
361 this->writeFields();
362 this->writef("private:\n");
363 this->writeConstructor();
364 this->writef(" GrGLSLFragmentProcessor* onCreateGLSLInstance() const override;\n"
365 " void onGetGLSLProcessorKey(const GrShaderCaps&, "
366 "GrProcessorKeyBuilder*) const override;\n"
367 " bool onIsEqual(const GrFragmentProcessor&) const override;\n");
368 for (const auto& param : fSectionAndParameterHelper.getParameters()) {
369 if (param->fType.kind() == Type::kSampler_Kind) {
370 this->writef(" const TextureSampler& onTextureSampler(int) const override;");
371 break;
372 }
373 }
374 this->writef("#if GR_TEST_UTILS\n"
375 " SkString onDumpInfo() const override;\n"
376 "#endif\n"
377 " GR_DECLARE_FRAGMENT_PROCESSOR_TEST\n"
378 " typedef GrFragmentProcessor INHERITED;\n"
379 "};\n");
380 this->writeSection(kHeaderEndSection);
381 this->writef("#endif\n");
382 return 0 == fErrors.errorCount();
383}
384
385} // namespace SkSL
386