1 //
2 // Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
3 // Copyright (C) 2012-2013 LunarG, Inc.
4 // Copyright (C) 2017 ARM Limited.
5 // Copyright (C) 2015-2018 Google, Inc.
6 // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights reserved.
7 //
8 // All rights reserved.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions
12 // are met:
13 //
14 // Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // Redistributions in binary form must reproduce the above
18 // copyright notice, this list of conditions and the following
19 // disclaimer in the documentation and/or other materials provided
20 // with the distribution.
21 //
22 // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
23 // contributors may be used to endorse or promote products derived
24 // from this software without specific prior written permission.
25 //
26 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
27 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
29 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
30 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
31 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
32 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
33 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
34 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
36 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 // POSSIBILITY OF SUCH DAMAGE.
38 //
39
40 //
41 // Symbol table for parsing. Most functionality and main ideas
42 // are documented in the header file.
43 //
44
45 #include "SymbolTable.h"
46
47 namespace glslang {
48
49 //
50 // TType helper function needs a place to live.
51 //
52
53 //
54 // Recursively generate mangled names.
55 //
buildMangledName(TString & mangledName) const56 void TType::buildMangledName(TString& mangledName) const
57 {
58 if (isMatrix())
59 mangledName += 'm';
60 else if (isVector())
61 mangledName += 'v';
62
63 switch (basicType) {
64 case EbtFloat: mangledName += 'f'; break;
65 case EbtInt: mangledName += 'i'; break;
66 case EbtUint: mangledName += 'u'; break;
67 case EbtBool: mangledName += 'b'; break;
68 case EbtDouble: mangledName += 'd'; break;
69 case EbtFloat16: mangledName += "f16"; break;
70 case EbtInt8: mangledName += "i8"; break;
71 case EbtUint8: mangledName += "u8"; break;
72 case EbtInt16: mangledName += "i16"; break;
73 case EbtUint16: mangledName += "u16"; break;
74 case EbtInt64: mangledName += "i64"; break;
75 case EbtUint64: mangledName += "u64"; break;
76 case EbtAtomicUint: mangledName += "au"; break;
77 case EbtAccStruct: mangledName += "as"; break;
78 case EbtRayQuery: mangledName += "rq"; break;
79 case EbtSpirvType: mangledName += "spv-t"; break;
80 case EbtHitObjectNV: mangledName += "ho"; break;
81 case EbtSampler:
82 switch (sampler.type) {
83 case EbtFloat16: mangledName += "f16"; break;
84 case EbtInt: mangledName += "i"; break;
85 case EbtUint: mangledName += "u"; break;
86 case EbtInt64: mangledName += "i64"; break;
87 case EbtUint64: mangledName += "u64"; break;
88 default: break; // some compilers want this
89 }
90 if (sampler.isImageClass())
91 mangledName += "I"; // a normal image or subpass
92 else if (sampler.isPureSampler())
93 mangledName += "p"; // a "pure" sampler
94 else if (!sampler.isCombined())
95 mangledName += "t"; // a "pure" texture
96 else
97 mangledName += "s"; // traditional combined sampler
98 if (sampler.isArrayed())
99 mangledName += "A";
100 if (sampler.isShadow())
101 mangledName += "S";
102 if (sampler.isExternal())
103 mangledName += "E";
104 if (sampler.isYuv())
105 mangledName += "Y";
106 switch (sampler.dim) {
107 case Esd2D: mangledName += "2"; break;
108 case Esd3D: mangledName += "3"; break;
109 case EsdCube: mangledName += "C"; break;
110 case Esd1D: mangledName += "1"; break;
111 case EsdRect: mangledName += "R2"; break;
112 case EsdBuffer: mangledName += "B"; break;
113 case EsdSubpass: mangledName += "P"; break;
114 default: break; // some compilers want this
115 }
116
117 #ifdef ENABLE_HLSL
118 if (sampler.hasReturnStruct()) {
119 // Name mangle for sampler return struct uses struct table index.
120 mangledName += "-tx-struct";
121
122 char text[16]; // plenty enough space for the small integers.
123 snprintf(text, sizeof(text), "%u-", sampler.getStructReturnIndex());
124 mangledName += text;
125 } else {
126 switch (sampler.getVectorSize()) {
127 case 1: mangledName += "1"; break;
128 case 2: mangledName += "2"; break;
129 case 3: mangledName += "3"; break;
130 case 4: break; // default to prior name mangle behavior
131 }
132 }
133 #endif
134
135 if (sampler.isMultiSample())
136 mangledName += "M";
137 break;
138 case EbtStruct:
139 case EbtBlock:
140 if (basicType == EbtStruct)
141 mangledName += "struct-";
142 else
143 mangledName += "block-";
144 if (typeName)
145 mangledName += *typeName;
146 for (unsigned int i = 0; i < structure->size(); ++i) {
147 if ((*structure)[i].type->getBasicType() == EbtVoid)
148 continue;
149 mangledName += '-';
150 (*structure)[i].type->buildMangledName(mangledName);
151 }
152 default:
153 break;
154 }
155
156 if (getVectorSize() > 0)
157 mangledName += static_cast<char>('0' + getVectorSize());
158 else {
159 mangledName += static_cast<char>('0' + getMatrixCols());
160 mangledName += static_cast<char>('0' + getMatrixRows());
161 }
162
163 if (arraySizes) {
164 const int maxSize = 11;
165 char buf[maxSize];
166 for (int i = 0; i < arraySizes->getNumDims(); ++i) {
167 if (arraySizes->getDimNode(i)) {
168 if (arraySizes->getDimNode(i)->getAsSymbolNode())
169 snprintf(buf, maxSize, "s%lld", arraySizes->getDimNode(i)->getAsSymbolNode()->getId());
170 else
171 snprintf(buf, maxSize, "s%p", arraySizes->getDimNode(i));
172 } else
173 snprintf(buf, maxSize, "%d", arraySizes->getDimSize(i));
174 mangledName += '[';
175 mangledName += buf;
176 mangledName += ']';
177 }
178 }
179 }
180
181 //
182 // Dump functions.
183 //
184
dumpExtensions(TInfoSink & infoSink) const185 void TSymbol::dumpExtensions(TInfoSink& infoSink) const
186 {
187 int numExtensions = getNumExtensions();
188 if (numExtensions) {
189 infoSink.debug << " <";
190
191 for (int i = 0; i < numExtensions; i++)
192 infoSink.debug << getExtensions()[i] << ",";
193
194 infoSink.debug << ">";
195 }
196 }
197
dump(TInfoSink & infoSink,bool complete) const198 void TVariable::dump(TInfoSink& infoSink, bool complete) const
199 {
200 if (complete) {
201 infoSink.debug << getName().c_str() << ": " << type.getCompleteString();
202 dumpExtensions(infoSink);
203 } else {
204 infoSink.debug << getName().c_str() << ": " << type.getStorageQualifierString() << " "
205 << type.getBasicTypeString();
206
207 if (type.isArray())
208 infoSink.debug << "[0]";
209 }
210
211 infoSink.debug << "\n";
212 }
213
dump(TInfoSink & infoSink,bool complete) const214 void TFunction::dump(TInfoSink& infoSink, bool complete) const
215 {
216 if (complete) {
217 infoSink.debug << getName().c_str() << ": " << returnType.getCompleteString() << " " << getName().c_str()
218 << "(";
219
220 int numParams = getParamCount();
221 for (int i = 0; i < numParams; i++) {
222 const TParameter ¶m = parameters[i];
223 infoSink.debug << param.type->getCompleteString() << " "
224 << (param.type->isStruct() ? "of " + param.type->getTypeName() + " " : "")
225 << (param.name ? *param.name : "") << (i < numParams - 1 ? "," : "");
226 }
227
228 infoSink.debug << ")";
229 dumpExtensions(infoSink);
230 } else {
231 infoSink.debug << getName().c_str() << ": " << returnType.getBasicTypeString() << " "
232 << getMangledName().c_str() << "n";
233 }
234
235 infoSink.debug << "\n";
236 }
237
dump(TInfoSink & TInfoSink,bool) const238 void TAnonMember::dump(TInfoSink& TInfoSink, bool) const
239 {
240 TInfoSink.debug << "anonymous member " << getMemberNumber() << " of " << getAnonContainer().getName().c_str()
241 << "\n";
242 }
243
dump(TInfoSink & infoSink,bool complete) const244 void TSymbolTableLevel::dump(TInfoSink& infoSink, bool complete) const
245 {
246 tLevel::const_iterator it;
247 for (it = level.begin(); it != level.end(); ++it)
248 (*it).second->dump(infoSink, complete);
249 }
250
dump(TInfoSink & infoSink,bool complete) const251 void TSymbolTable::dump(TInfoSink& infoSink, bool complete) const
252 {
253 for (int level = currentLevel(); level >= 0; --level) {
254 infoSink.debug << "LEVEL " << level << "\n";
255 table[level]->dump(infoSink, complete);
256 }
257 }
258
259 //
260 // Functions have buried pointers to delete.
261 //
~TFunction()262 TFunction::~TFunction()
263 {
264 for (TParamList::iterator i = parameters.begin(); i != parameters.end(); ++i)
265 delete (*i).type;
266 }
267
268 //
269 // Symbol table levels are a map of pointers to symbols that have to be deleted.
270 //
~TSymbolTableLevel()271 TSymbolTableLevel::~TSymbolTableLevel()
272 {
273 for (tLevel::iterator it = level.begin(); it != level.end(); ++it) {
274 const TString& name = it->first;
275 auto retargetIter = std::find_if(retargetedSymbols.begin(), retargetedSymbols.end(),
276 [&name](const std::pair<TString, TString>& i) { return i.first == name; });
277 if (retargetIter == retargetedSymbols.end())
278 delete (*it).second;
279 }
280
281
282 delete [] defaultPrecision;
283 }
284
285 //
286 // Change all function entries in the table with the non-mangled name
287 // to be related to the provided built-in operation.
288 //
relateToOperator(const char * name,TOperator op)289 void TSymbolTableLevel::relateToOperator(const char* name, TOperator op)
290 {
291 tLevel::const_iterator candidate = level.lower_bound(name);
292 while (candidate != level.end()) {
293 const TString& candidateName = (*candidate).first;
294 TString::size_type parenAt = candidateName.find_first_of('(');
295 if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
296 TFunction* function = (*candidate).second->getAsFunction();
297 function->relateToOperator(op);
298 } else
299 break;
300 ++candidate;
301 }
302 }
303
304 // Make all function overloads of the given name require an extension(s).
305 // Should only be used for a version/profile that actually needs the extension(s).
setFunctionExtensions(const char * name,int num,const char * const extensions[])306 void TSymbolTableLevel::setFunctionExtensions(const char* name, int num, const char* const extensions[])
307 {
308 tLevel::const_iterator candidate = level.lower_bound(name);
309 while (candidate != level.end()) {
310 const TString& candidateName = (*candidate).first;
311 TString::size_type parenAt = candidateName.find_first_of('(');
312 if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
313 TSymbol* symbol = candidate->second;
314 symbol->setExtensions(num, extensions);
315 } else
316 break;
317 ++candidate;
318 }
319 }
320
321 // Make a single function require an extension(s). i.e., this will only set the extensions for the symbol that matches 'name' exactly.
322 // This is different from setFunctionExtensions, which uses std::map::lower_bound to effectively set all symbols that start with 'name'.
323 // Should only be used for a version/profile that actually needs the extension(s).
setSingleFunctionExtensions(const char * name,int num,const char * const extensions[])324 void TSymbolTableLevel::setSingleFunctionExtensions(const char* name, int num, const char* const extensions[])
325 {
326 if (auto candidate = level.find(name); candidate != level.end()) {
327 candidate->second->setExtensions(num, extensions);
328 }
329 }
330
331 //
332 // Make all symbols in this table level read only.
333 //
readOnly()334 void TSymbolTableLevel::readOnly()
335 {
336 for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
337 (*it).second->makeReadOnly();
338 }
339
340 //
341 // Copy a symbol, but the copy is writable; call readOnly() afterward if that's not desired.
342 //
TSymbol(const TSymbol & copyOf)343 TSymbol::TSymbol(const TSymbol& copyOf)
344 {
345 name = NewPoolTString(copyOf.name->c_str());
346 uniqueId = copyOf.uniqueId;
347 writable = true;
348 }
349
TVariable(const TVariable & copyOf)350 TVariable::TVariable(const TVariable& copyOf) : TSymbol(copyOf)
351 {
352 type.deepCopy(copyOf.type);
353 userType = copyOf.userType;
354
355 // we don't support specialization-constant subtrees in cloned tables, only extensions
356 constSubtree = nullptr;
357 extensions = nullptr;
358 memberExtensions = nullptr;
359 if (copyOf.getNumExtensions() > 0)
360 setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
361 if (copyOf.hasMemberExtensions()) {
362 for (int m = 0; m < (int)copyOf.type.getStruct()->size(); ++m) {
363 if (copyOf.getNumMemberExtensions(m) > 0)
364 setMemberExtensions(m, copyOf.getNumMemberExtensions(m), copyOf.getMemberExtensions(m));
365 }
366 }
367
368 if (! copyOf.constArray.empty()) {
369 assert(! copyOf.type.isStruct());
370 TConstUnionArray newArray(copyOf.constArray, 0, copyOf.constArray.size());
371 constArray = newArray;
372 }
373 }
374
clone() const375 TVariable* TVariable::clone() const
376 {
377 TVariable *variable = new TVariable(*this);
378
379 return variable;
380 }
381
TFunction(const TFunction & copyOf)382 TFunction::TFunction(const TFunction& copyOf) : TSymbol(copyOf)
383 {
384 for (unsigned int i = 0; i < copyOf.parameters.size(); ++i) {
385 TParameter param{};
386 parameters.push_back(param);
387 (void)parameters.back().copyParam(copyOf.parameters[i]);
388 }
389
390 extensions = nullptr;
391 if (copyOf.getNumExtensions() > 0)
392 setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
393 returnType.deepCopy(copyOf.returnType);
394 mangledName = copyOf.mangledName;
395 op = copyOf.op;
396 defined = copyOf.defined;
397 prototyped = copyOf.prototyped;
398 implicitThis = copyOf.implicitThis;
399 illegalImplicitThis = copyOf.illegalImplicitThis;
400 defaultParamCount = copyOf.defaultParamCount;
401 spirvInst = copyOf.spirvInst;
402 }
403
clone() const404 TFunction* TFunction::clone() const
405 {
406 TFunction *function = new TFunction(*this);
407
408 return function;
409 }
410
clone() const411 TAnonMember* TAnonMember::clone() const
412 {
413 // Anonymous members of a given block should be cloned at a higher level,
414 // where they can all be assured to still end up pointing to a single
415 // copy of the original container.
416 assert(0);
417
418 return nullptr;
419 }
420
clone() const421 TSymbolTableLevel* TSymbolTableLevel::clone() const
422 {
423 TSymbolTableLevel *symTableLevel = new TSymbolTableLevel();
424 symTableLevel->anonId = anonId;
425 symTableLevel->thisLevel = thisLevel;
426 symTableLevel->retargetedSymbols.clear();
427 for (auto &s : retargetedSymbols) {
428 symTableLevel->retargetedSymbols.push_back({s.first, s.second});
429 }
430 std::vector<bool> containerCopied(anonId, false);
431 tLevel::const_iterator iter;
432 for (iter = level.begin(); iter != level.end(); ++iter) {
433 const TAnonMember* anon = iter->second->getAsAnonMember();
434 if (anon) {
435 // Insert all the anonymous members of this same container at once,
436 // avoid inserting the remaining members in the future, once this has been done,
437 // allowing them to all be part of the same new container.
438 if (! containerCopied[anon->getAnonId()]) {
439 TVariable* container = anon->getAnonContainer().clone();
440 container->changeName(NewPoolTString(""));
441 // insert the container and all its members
442 symTableLevel->insert(*container, false);
443 containerCopied[anon->getAnonId()] = true;
444 }
445 } else {
446 const TString& name = iter->first;
447 auto retargetIter = std::find_if(retargetedSymbols.begin(), retargetedSymbols.end(),
448 [&name](const std::pair<TString, TString>& i) { return i.first == name; });
449 if (retargetIter != retargetedSymbols.end())
450 continue;
451 symTableLevel->insert(*iter->second->clone(), false);
452 }
453 }
454 // Now point retargeted symbols to the newly created versions of them
455 for (auto &s : retargetedSymbols) {
456 TSymbol* sym = symTableLevel->find(s.second);
457 if (!sym)
458 continue;
459 symTableLevel->insert(s.first, sym);
460 }
461
462 return symTableLevel;
463 }
464
copyTable(const TSymbolTable & copyOf)465 void TSymbolTable::copyTable(const TSymbolTable& copyOf)
466 {
467 assert(adoptedLevels == copyOf.adoptedLevels);
468
469 uniqueId = copyOf.uniqueId;
470 noBuiltInRedeclarations = copyOf.noBuiltInRedeclarations;
471 separateNameSpaces = copyOf.separateNameSpaces;
472 for (unsigned int i = copyOf.adoptedLevels; i < copyOf.table.size(); ++i)
473 table.push_back(copyOf.table[i]->clone());
474 }
475
476 } // end namespace glslang
477