1 /*
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/SkSLMangler.h"
9
10 #include "include/core/SkString.h"
11 #include "include/core/SkTypes.h"
12 #include "src/base/SkStringView.h"
13 #include "src/sksl/ir/SkSLSymbolTable.h"
14
15 #include <algorithm>
16 #include <cstring>
17 #include <ctype.h>
18
19 namespace SkSL {
20
uniqueName(std::string_view baseName,SymbolTable * symbolTable)21 std::string Mangler::uniqueName(std::string_view baseName, SymbolTable* symbolTable) {
22 SkASSERT(symbolTable);
23
24 // Private names might begin with a $. Strip that off.
25 if (skstd::starts_with(baseName, '$')) {
26 baseName.remove_prefix(1);
27 }
28
29 // The inliner runs more than once, so the base name might already have been mangled and have a
30 // prefix like "_123_x". Let's strip that prefix off to make the generated code easier to read.
31 if (skstd::starts_with(baseName, '_')) {
32 // Determine if we have a string of digits.
33 int offset = 1;
34 while (isdigit(baseName[offset])) {
35 ++offset;
36 }
37 // If we found digits, another underscore, and anything else, that's the mangler prefix.
38 // Strip it off.
39 if (offset > 1 && baseName[offset] == '_' && baseName[offset + 1] != '\0') {
40 baseName.remove_prefix(offset + 1);
41 } else {
42 // This name doesn't contain a mangler prefix, but it does start with an underscore.
43 // OpenGL disallows two consecutive underscores anywhere in the string, and we'll be
44 // adding one as part of the mangler prefix, so strip the leading underscore.
45 baseName.remove_prefix(1);
46 }
47 }
48
49 // Append a unique numeric prefix to avoid name overlap. Check the symbol table to make sure
50 // we're not reusing an existing name. (Note that within a single compilation pass, this check
51 // isn't fully comprehensive, as code isn't always generated in top-to-bottom order.)
52
53 // This code is a performance hotspot. Assemble the string manually to save a few cycles.
54 char uniqueName[256];
55 uniqueName[0] = '_';
56 char* uniqueNameEnd = uniqueName + std::size(uniqueName);
57 for (;;) {
58 // _123
59 char* endPtr = SkStrAppendS32(uniqueName + 1, fCounter++);
60
61 // _123_
62 *endPtr++ = '_';
63
64 // _123_baseNameTruncatedToFit (no null terminator, because string_view doesn't require one)
65 int baseNameCopyLength = std::min<int>(baseName.size(), uniqueNameEnd - endPtr);
66 memcpy(endPtr, baseName.data(), baseNameCopyLength);
67 endPtr += baseNameCopyLength;
68
69 std::string_view uniqueNameView(uniqueName, endPtr - uniqueName);
70 if (symbolTable->find(uniqueNameView) == nullptr) {
71 return std::string(uniqueNameView);
72 }
73 }
74 }
75
76 } // namespace SkSL
77