blob: d5a447cc14050c6ca9f69c9f42e2ad9cb9a921da [file] [log] [blame]
Ethan Nicholas371f6e12021-05-04 14:30:02 -04001/*
2 * Copyright 2021 Google LLC.
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/ir/SkSLFunctionDeclaration.h"
9
10#include "src/sksl/SkSLCompiler.h"
11#include "src/sksl/SkSLIRGenerator.h"
12#include "src/sksl/ir/SkSLUnresolvedFunction.h"
13
14namespace SkSL {
15
John Stilesf96cb712021-05-05 22:17:04 -040016static IntrinsicKind identify_intrinsic(const String& functionName) {
17 #define SKSL_INTRINSIC(name) {#name, k_##name##_IntrinsicKind},
18 static const auto* kAllIntrinsics = new std::unordered_map<String, IntrinsicKind>{
19 SKSL_INTRINSIC_LIST
20 };
21 #undef SKSL_INTRINSIC
22
23 auto iter = kAllIntrinsics->find(functionName);
24 if (iter != kAllIntrinsics->end()) {
25 return iter->second;
26 }
27
28 return kNotIntrinsic;
29}
30
John Stilesefde90d2021-08-12 23:06:24 -040031static bool check_modifiers(const Context& context,
32 int offset,
33 const Modifiers& modifiers,
34 bool isBuiltin) {
35 const int permitted = Modifiers::kHasSideEffects_Flag |
36 Modifiers::kInline_Flag |
37 Modifiers::kNoInline_Flag |
38 (isBuiltin ? Modifiers::kES3_Flag : 0);
39 IRGenerator::CheckModifiers(context, offset, modifiers, permitted, /*permittedLayoutFlags=*/0);
Ethan Nicholas371f6e12021-05-04 14:30:02 -040040 if ((modifiers.fFlags & Modifiers::kInline_Flag) &&
41 (modifiers.fFlags & Modifiers::kNoInline_Flag)) {
Ethan Nicholas8d116542021-08-11 13:27:16 -040042 context.errors().error(offset, "functions cannot be both 'inline' and 'noinline'");
Ethan Nicholas371f6e12021-05-04 14:30:02 -040043 return false;
44 }
45 return true;
46}
47
48static bool check_return_type(const Context& context, int offset, const Type& returnType,
49 bool isBuiltin) {
Ethan Nicholas8d116542021-08-11 13:27:16 -040050 ErrorReporter& errors = context.errors();
Ethan Nicholas371f6e12021-05-04 14:30:02 -040051 if (returnType.isArray()) {
52 errors.error(offset, "functions may not return type '" + returnType.displayName() + "'");
53 return false;
54 }
55 if (context.fConfig->strictES2Mode() && returnType.isOrContainsArray()) {
56 errors.error(offset, "functions may not return structs containing arrays");
57 return false;
58 }
59 if (!isBuiltin && !returnType.isVoid() && returnType.componentType().isOpaque()) {
60 errors.error(offset, "functions may not return opaque type '" + returnType.displayName() +
61 "'");
62 return false;
63 }
64 return true;
65}
66
John Stiles0b822792021-05-04 17:41:53 -040067static bool check_parameters(const Context& context,
Ethan Nicholas371f6e12021-05-04 14:30:02 -040068 std::vector<std::unique_ptr<Variable>>& parameters, bool isMain,
69 bool isBuiltin) {
70 auto typeIsValidForColor = [&](const Type& type) {
71 return type == *context.fTypes.fHalf4 || type == *context.fTypes.fFloat4;
72 };
73
John Stiles9c19b9f2021-06-10 09:43:35 -040074 // The first color parameter passed to main() is the input color; the second is the dest color.
John Stiles50d0d092021-06-09 17:24:31 -040075 static constexpr int kBuiltinColorIDs[] = {SK_INPUT_COLOR_BUILTIN, SK_DEST_COLOR_BUILTIN};
76 unsigned int builtinColorIndex = 0;
77
John Stiles9c19b9f2021-06-10 09:43:35 -040078 // Check modifiers on each function parameter.
Ethan Nicholas371f6e12021-05-04 14:30:02 -040079 for (auto& param : parameters) {
80 IRGenerator::CheckModifiers(context, param->fOffset, param->modifiers(),
81 Modifiers::kConst_Flag | Modifiers::kIn_Flag |
82 Modifiers::kOut_Flag, /*permittedLayoutFlags=*/0);
83 const Type& type = param->type();
84 // Only the (builtin) declarations of 'sample' are allowed to have shader/colorFilter or FP
85 // parameters. You can pass other opaque types to functions safely; this restriction is
86 // specific to "child" objects.
Brian Osman8c264792021-07-01 16:41:27 -040087 if (type.isEffectChild() && !isBuiltin) {
Ethan Nicholas8d116542021-08-11 13:27:16 -040088 context.errors().error(param->fOffset, "parameters of type '" + type.displayName() +
89 "' not allowed");
Ethan Nicholas371f6e12021-05-04 14:30:02 -040090 return false;
91 }
92
93 Modifiers m = param->modifiers();
John Stilesbb2ef922021-07-26 08:32:07 -040094 if (isMain) {
John Stilesaddccaf2021-08-02 19:03:30 -040095 if (ProgramConfig::IsRuntimeEffect(context.fConfig->fKind)) {
John Stilesbb2ef922021-07-26 08:32:07 -040096 // We verify that the signature is fully correct later. For now, if this is a
97 // runtime effect of any flavor, a float2 param is supposed to be the coords, and a
98 // half4/float parameter is supposed to be the input or destination color:
99 if (type == *context.fTypes.fFloat2) {
100 m.fLayout.fBuiltin = SK_MAIN_COORDS_BUILTIN;
101 } else if (typeIsValidForColor(type) &&
102 builtinColorIndex < SK_ARRAY_COUNT(kBuiltinColorIDs)) {
103 m.fLayout.fBuiltin = kBuiltinColorIDs[builtinColorIndex++];
104 }
105 if (m.fLayout.fBuiltin) {
106 param->setModifiers(context.fModifiersPool->add(m));
107 }
108 } else if (context.fConfig->fKind == ProgramKind::kFragment) {
109 // For testing purposes, we have .sksl inputs that are treated as both runtime
110 // effects and fragment shaders. To make that work, fragment shaders are allowed to
John Stiles9078a892021-08-18 15:03:17 -0400111 // have a coords parameter.
John Stilesbb2ef922021-07-26 08:32:07 -0400112 if (type == *context.fTypes.fFloat2) {
John Stiles9078a892021-08-18 15:03:17 -0400113 m.fLayout.fBuiltin = SK_MAIN_COORDS_BUILTIN;
John Stilesbb2ef922021-07-26 08:32:07 -0400114 param->setModifiers(context.fModifiersPool->add(m));
115 }
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400116 }
117 }
118 }
119 return true;
120}
121
122static bool check_main_signature(const Context& context, int offset, const Type& returnType,
123 std::vector<std::unique_ptr<Variable>>& parameters,
124 bool isBuiltin) {
Ethan Nicholas8d116542021-08-11 13:27:16 -0400125 ErrorReporter& errors = context.errors();
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400126 ProgramKind kind = context.fConfig->fKind;
127
128 auto typeIsValidForColor = [&](const Type& type) {
129 return type == *context.fTypes.fHalf4 || type == *context.fTypes.fFloat4;
130 };
131
132 auto paramIsCoords = [&](int idx) {
133 const Variable& p = *parameters[idx];
134 return p.type() == *context.fTypes.fFloat2 &&
135 p.modifiers().fFlags == 0 &&
John Stiles9078a892021-08-18 15:03:17 -0400136 p.modifiers().fLayout.fBuiltin == SK_MAIN_COORDS_BUILTIN;
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400137 };
138
John Stiles50d0d092021-06-09 17:24:31 -0400139 auto paramIsBuiltinColor = [&](int idx, int builtinID) {
140 const Variable& p = *parameters[idx];
141 return typeIsValidForColor(p.type()) &&
142 p.modifiers().fFlags == 0 &&
143 p.modifiers().fLayout.fBuiltin == builtinID;
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400144 };
145
John Stiles50d0d092021-06-09 17:24:31 -0400146 auto paramIsInputColor = [&](int n) { return paramIsBuiltinColor(n, SK_INPUT_COLOR_BUILTIN); };
147 auto paramIsDestColor = [&](int n) { return paramIsBuiltinColor(n, SK_DEST_COLOR_BUILTIN); };
148
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400149 switch (kind) {
150 case ProgramKind::kRuntimeColorFilter: {
151 // (half4|float4) main(half4|float4)
152 if (!typeIsValidForColor(returnType)) {
153 errors.error(offset, "'main' must return: 'vec4', 'float4', or 'half4'");
154 return false;
155 }
156 bool validParams = (parameters.size() == 1 && paramIsInputColor(0));
157 if (!validParams) {
158 errors.error(offset, "'main' parameter must be 'vec4', 'float4', or 'half4'");
159 return false;
160 }
161 break;
162 }
163 case ProgramKind::kRuntimeShader: {
164 // (half4|float4) main(float2) -or- (half4|float4) main(float2, half4|float4)
165 if (!typeIsValidForColor(returnType)) {
166 errors.error(offset, "'main' must return: 'vec4', 'float4', or 'half4'");
167 return false;
168 }
169 bool validParams =
170 (parameters.size() == 1 && paramIsCoords(0)) ||
171 (parameters.size() == 2 && paramIsCoords(0) && paramIsInputColor(1));
172 if (!validParams) {
173 errors.error(offset, "'main' parameters must be (float2, (vec4|float4|half4)?)");
174 return false;
175 }
176 break;
177 }
John Stiles2d8b8352021-06-16 11:33:13 -0400178 case ProgramKind::kRuntimeBlender: {
John Stilesf7f36ae2021-06-08 14:06:22 -0400179 // (half4|float4) main(half4|float4, half4|float4)
180 if (!typeIsValidForColor(returnType)) {
181 errors.error(offset, "'main' must return: 'vec4', 'float4', or 'half4'");
182 return false;
183 }
184 if (!(parameters.size() == 2 &&
185 paramIsInputColor(0) &&
John Stiles50d0d092021-06-09 17:24:31 -0400186 paramIsDestColor(1))) {
John Stilesf7f36ae2021-06-08 14:06:22 -0400187 errors.error(offset, "'main' parameters must be (vec4|float4|half4, "
188 "vec4|float4|half4)");
189 return false;
190 }
191 break;
192 }
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400193 case ProgramKind::kGeneric:
194 // No rules apply here
195 break;
196 case ProgramKind::kFragment: {
197 bool validParams = (parameters.size() == 0) ||
198 (parameters.size() == 1 && paramIsCoords(0));
199 if (!validParams) {
200 errors.error(offset, "shader 'main' must be main() or main(float2)");
201 return false;
202 }
203 break;
204 }
205 case ProgramKind::kVertex:
206 case ProgramKind::kGeometry:
207 if (parameters.size()) {
208 errors.error(offset, "shader 'main' must have zero parameters");
209 return false;
210 }
211 break;
212 }
213 return true;
214}
215
216/**
217 * Checks for a previously existing declaration of this function, reporting errors if there is an
218 * incompatible symbol. Returns true and sets outExistingDecl to point to the existing declaration
219 * (or null if none) on success, returns false on error.
220 */
221static bool find_existing_declaration(const Context& context, SymbolTable& symbols, int offset,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400222 skstd::string_view name,
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400223 std::vector<std::unique_ptr<Variable>>& parameters,
224 const Type* returnType, bool isBuiltin,
225 const FunctionDeclaration** outExistingDecl) {
Ethan Nicholas8d116542021-08-11 13:27:16 -0400226 ErrorReporter& errors = context.errors();
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400227 const Symbol* entry = symbols[name];
228 *outExistingDecl = nullptr;
229 if (entry) {
230 std::vector<const FunctionDeclaration*> functions;
231 switch (entry->kind()) {
232 case Symbol::Kind::kUnresolvedFunction:
233 functions = entry->as<UnresolvedFunction>().functions();
234 break;
235 case Symbol::Kind::kFunctionDeclaration:
236 functions.push_back(&entry->as<FunctionDeclaration>());
237 break;
238 default:
239 errors.error(offset, "symbol '" + name + "' was already defined");
240 return false;
241 }
242 for (const FunctionDeclaration* other : functions) {
243 SkASSERT(name == other->name());
244 if (parameters.size() != other->parameters().size()) {
245 continue;
246 }
247 bool match = true;
248 for (size_t i = 0; i < parameters.size(); i++) {
249 if (parameters[i]->type() != other->parameters()[i]->type()) {
250 match = false;
251 break;
252 }
253 }
254 if (!match) {
255 continue;
256 }
257 if (*returnType != other->returnType()) {
258 std::vector<const Variable*> paramPtrs;
259 paramPtrs.reserve(parameters.size());
260 for (std::unique_ptr<Variable>& param : parameters) {
261 paramPtrs.push_back(param.get());
262 }
263 FunctionDeclaration invalidDecl(offset,
264 &other->modifiers(),
265 name,
266 std::move(paramPtrs),
267 returnType,
268 isBuiltin);
269 errors.error(offset,
270 "functions '" + invalidDecl.description() + "' and '" +
271 other->description() + "' differ only in return type");
272 return false;
273 }
274 for (size_t i = 0; i < parameters.size(); i++) {
275 if (parameters[i]->modifiers() != other->parameters()[i]->modifiers()) {
276 errors.error(offset,
277 "modifiers on parameter " + to_string((uint64_t)i + 1) +
278 " differ between declaration and definition");
279 return false;
280 }
281 }
282 if (other->definition() && !other->isBuiltin()) {
283 errors.error(offset, "duplicate definition of " + other->description());
284 return false;
285 }
286 *outExistingDecl = other;
287 break;
288 }
289 }
290 return true;
291}
292
John Stilesf96cb712021-05-05 22:17:04 -0400293FunctionDeclaration::FunctionDeclaration(int offset,
294 const Modifiers* modifiers,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400295 skstd::string_view name,
John Stilesf96cb712021-05-05 22:17:04 -0400296 std::vector<const Variable*> parameters,
297 const Type* returnType,
298 bool builtin)
299 : INHERITED(offset, kSymbolKind, name, /*type=*/nullptr)
300 , fDefinition(nullptr)
301 , fModifiers(modifiers)
302 , fParameters(std::move(parameters))
303 , fReturnType(returnType)
304 , fBuiltin(builtin)
305 , fIsMain(name == "main")
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400306 , fIntrinsicKind(builtin ? identify_intrinsic(String(name)) : kNotIntrinsic) {}
John Stilesf96cb712021-05-05 22:17:04 -0400307
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400308const FunctionDeclaration* FunctionDeclaration::Convert(const Context& context,
John Stiles0b822792021-05-04 17:41:53 -0400309 SymbolTable& symbols, int offset, const Modifiers* modifiers,
Ethan Nicholas962dec42021-06-10 13:06:39 -0400310 skstd::string_view name, std::vector<std::unique_ptr<Variable>> parameters,
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400311 const Type* returnType, bool isBuiltin) {
312 bool isMain = (name == "main");
313
314 const FunctionDeclaration* decl = nullptr;
John Stilesefde90d2021-08-12 23:06:24 -0400315 if (!check_modifiers(context, offset, *modifiers, isBuiltin) ||
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400316 !check_return_type(context, offset, *returnType, isBuiltin) ||
John Stiles0b822792021-05-04 17:41:53 -0400317 !check_parameters(context, parameters, isMain, isBuiltin) ||
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400318 (isMain && !check_main_signature(context, offset, *returnType, parameters, isBuiltin)) ||
319 !find_existing_declaration(context, symbols, offset, name, parameters, returnType,
320 isBuiltin, &decl)) {
321 return nullptr;
322 }
323 std::vector<const Variable*> finalParameters;
324 finalParameters.reserve(parameters.size());
John Stilesf96cb712021-05-05 22:17:04 -0400325 for (std::unique_ptr<Variable>& param : parameters) {
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400326 finalParameters.push_back(symbols.takeOwnershipOfSymbol(std::move(param)));
327 }
328 if (decl) {
329 return decl;
330 }
331 auto result = std::make_unique<FunctionDeclaration>(offset, modifiers, name,
332 std::move(finalParameters), returnType,
333 isBuiltin);
334 return symbols.add(std::move(result));
335}
336
John Stilesf96cb712021-05-05 22:17:04 -0400337String FunctionDeclaration::mangledName() const {
338 if ((this->isBuiltin() && !this->definition()) || this->isMain()) {
339 // Builtins without a definition (like `sin` or `sqrt`) must use their real names.
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400340 return String(this->name());
John Stilesf96cb712021-05-05 22:17:04 -0400341 }
342 // GLSL forbids two underscores in a row; add an extra character if necessary to avoid this.
Ethan Nicholasd2e09602021-06-10 11:21:59 -0400343 const char* splitter = this->name().ends_with("_") ? "x_" : "_";
John Stilesf96cb712021-05-05 22:17:04 -0400344 // Rename function to `funcname_returntypeparamtypes`.
345 String result = this->name() + splitter + this->returnType().abbreviatedName();
346 for (const Variable* p : this->parameters()) {
347 result += p->type().abbreviatedName();
348 }
349 return result;
350}
351
352String FunctionDeclaration::description() const {
353 String result = this->returnType().displayName() + " " + this->name() + "(";
354 String separator;
355 for (const Variable* p : this->parameters()) {
356 result += separator;
357 separator = ", ";
358 result += p->type().displayName();
359 result += " ";
360 result += p->name();
361 }
362 result += ")";
363 return result;
364}
365
366bool FunctionDeclaration::matches(const FunctionDeclaration& f) const {
367 if (this->name() != f.name()) {
368 return false;
369 }
370 const std::vector<const Variable*>& parameters = this->parameters();
371 const std::vector<const Variable*>& otherParameters = f.parameters();
372 if (parameters.size() != otherParameters.size()) {
373 return false;
374 }
375 for (size_t i = 0; i < parameters.size(); i++) {
376 if (parameters[i]->type() != otherParameters[i]->type()) {
377 return false;
378 }
379 }
380 return true;
381}
382
383bool FunctionDeclaration::determineFinalTypes(const ExpressionArray& arguments,
384 ParamTypes* outParameterTypes,
385 const Type** outReturnType) const {
386 const std::vector<const Variable*>& parameters = this->parameters();
387 SkASSERT(arguments.size() == parameters.size());
388
389 outParameterTypes->reserve_back(arguments.size());
390 int genericIndex = -1;
391 for (size_t i = 0; i < arguments.size(); i++) {
392 // Non-generic parameters are final as-is.
393 const Type& parameterType = parameters[i]->type();
394 if (parameterType.typeKind() != Type::TypeKind::kGeneric) {
395 outParameterTypes->push_back(&parameterType);
396 continue;
397 }
398 // We use the first generic parameter we find to lock in the generic index;
399 // e.g. if we find `float3` here, all `$genType`s will be assumed to be `float3`.
400 const std::vector<const Type*>& types = parameterType.coercibleTypes();
401 if (genericIndex == -1) {
402 for (size_t j = 0; j < types.size(); j++) {
403 if (arguments[i]->type().canCoerceTo(*types[j], /*allowNarrowing=*/true)) {
404 genericIndex = j;
405 break;
406 }
407 }
408 if (genericIndex == -1) {
409 // The passed-in type wasn't a match for ANY of the generic possibilities.
410 // This function isn't a match at all.
411 return false;
412 }
413 }
414 outParameterTypes->push_back(types[genericIndex]);
415 }
416 // Apply the generic index to our return type.
417 const Type& returnType = this->returnType();
418 if (returnType.typeKind() == Type::TypeKind::kGeneric) {
419 if (genericIndex == -1) {
420 // We don't support functions with a generic return type and no other generics.
421 return false;
422 }
423 *outReturnType = returnType.coercibleTypes()[genericIndex];
424 } else {
425 *outReturnType = &returnType;
426 }
427 return true;
428}
429
Ethan Nicholas371f6e12021-05-04 14:30:02 -0400430} // namespace SkSL