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