Merge pull request #7 from KhronosGroup/master
[platform/upstream/glslang.git] / glslang / MachineIndependent / SymbolTable.cpp
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 //
7 // All rights reserved.
8 //
9 // Redistribution and use in source and binary forms, with or without
10 // modification, are permitted provided that the following conditions
11 // are met:
12 //
13 //    Redistributions of source code must retain the above copyright
14 //    notice, this list of conditions and the following disclaimer.
15 //
16 //    Redistributions in binary form must reproduce the above
17 //    copyright notice, this list of conditions and the following
18 //    disclaimer in the documentation and/or other materials provided
19 //    with the distribution.
20 //
21 //    Neither the name of 3Dlabs Inc. Ltd. nor the names of its
22 //    contributors may be used to endorse or promote products derived
23 //    from this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
26 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
27 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
28 // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
29 // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
30 // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
31 // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
32 // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
33 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 // POSSIBILITY OF SUCH DAMAGE.
37 //
38
39 //
40 // Symbol table for parsing.  Most functionality and main ideas
41 // are documented in the header file.
42 //
43
44 #include "SymbolTable.h"
45
46 namespace glslang {
47
48 //
49 // TType helper function needs a place to live.
50 //
51
52 //
53 // Recursively generate mangled names.
54 //
55 void TType::buildMangledName(TString& mangledName) const
56 {
57     if (isMatrix())
58         mangledName += 'm';
59     else if (isVector())
60         mangledName += 'v';
61
62     switch (basicType) {
63     case EbtFloat:              mangledName += 'f';      break;
64     case EbtInt:                mangledName += 'i';      break;
65     case EbtUint:               mangledName += 'u';      break;
66     case EbtBool:               mangledName += 'b';      break;
67 #ifndef GLSLANG_WEB
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 EbtAccStructNV:        mangledName += "asnv";   break;
78 #endif
79     case EbtSampler:
80         switch (sampler.type) {
81 #ifndef GLSLANG_WEB
82         case EbtFloat16: mangledName += "f16"; break;
83 #endif
84         case EbtInt:   mangledName += "i"; break;
85         case EbtUint:  mangledName += "u"; break;
86         default: break; // some compilers want this
87         }
88         if (sampler.isImageClass())
89             mangledName += "I";  // a normal image or subpass
90         else if (sampler.isPureSampler())
91             mangledName += "p";  // a "pure" sampler
92         else if (!sampler.isCombined())
93             mangledName += "t";  // a "pure" texture
94         else
95             mangledName += "s";  // traditional combined sampler
96         if (sampler.isArrayed())
97             mangledName += "A";
98         if (sampler.isShadow())
99             mangledName += "S";
100         if (sampler.isExternal())
101             mangledName += "E";
102         if (sampler.isYuv())
103             mangledName += "Y";
104         switch (sampler.dim) {
105         case Esd2D:       mangledName += "2";  break;
106         case Esd3D:       mangledName += "3";  break;
107         case EsdCube:     mangledName += "C";  break;
108 #ifndef GLSLANG_WEB
109         case Esd1D:       mangledName += "1";  break;
110         case EsdRect:     mangledName += "R2"; break;
111         case EsdBuffer:   mangledName += "B";  break;
112         case EsdSubpass:  mangledName += "P";  break;
113 #endif
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), "%d-", 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             mangledName += '-';
148             (*structure)[i].type->buildMangledName(mangledName);
149         }
150     default:
151         break;
152     }
153
154     if (getVectorSize() > 0)
155         mangledName += static_cast<char>('0' + getVectorSize());
156     else {
157         mangledName += static_cast<char>('0' + getMatrixCols());
158         mangledName += static_cast<char>('0' + getMatrixRows());
159     }
160
161     if (arraySizes) {
162         const int maxSize = 11;
163         char buf[maxSize];
164         for (int i = 0; i < arraySizes->getNumDims(); ++i) {
165             if (arraySizes->getDimNode(i)) {
166                 if (arraySizes->getDimNode(i)->getAsSymbolNode())
167                     snprintf(buf, maxSize, "s%d", arraySizes->getDimNode(i)->getAsSymbolNode()->getId());
168                 else
169                     snprintf(buf, maxSize, "s%p", arraySizes->getDimNode(i));
170             } else
171                 snprintf(buf, maxSize, "%d", arraySizes->getDimSize(i));
172             mangledName += '[';
173             mangledName += buf;
174             mangledName += ']';
175         }
176     }
177 }
178
179 #ifndef GLSLANG_WEB
180
181 //
182 // Dump functions.
183 //
184
185 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
198 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
214 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 &param = 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
238 void TAnonMember::dump(TInfoSink& TInfoSink, bool) const
239 {
240     TInfoSink.debug << "anonymous member " << getMemberNumber() << " of " << getAnonContainer().getName().c_str()
241                     << "\n";
242 }
243
244 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
251 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 #endif
260
261 //
262 // Functions have buried pointers to delete.
263 //
264 TFunction::~TFunction()
265 {
266     for (TParamList::iterator i = parameters.begin(); i != parameters.end(); ++i)
267         delete (*i).type;
268 }
269
270 //
271 // Symbol table levels are a map of pointers to symbols that have to be deleted.
272 //
273 TSymbolTableLevel::~TSymbolTableLevel()
274 {
275     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
276         delete (*it).second;
277
278     delete [] defaultPrecision;
279 }
280
281 //
282 // Change all function entries in the table with the non-mangled name
283 // to be related to the provided built-in operation.
284 //
285 void TSymbolTableLevel::relateToOperator(const char* name, TOperator op)
286 {
287     tLevel::const_iterator candidate = level.lower_bound(name);
288     while (candidate != level.end()) {
289         const TString& candidateName = (*candidate).first;
290         TString::size_type parenAt = candidateName.find_first_of('(');
291         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
292             TFunction* function = (*candidate).second->getAsFunction();
293             function->relateToOperator(op);
294         } else
295             break;
296         ++candidate;
297     }
298 }
299
300 // Make all function overloads of the given name require an extension(s).
301 // Should only be used for a version/profile that actually needs the extension(s).
302 void TSymbolTableLevel::setFunctionExtensions(const char* name, int num, const char* const extensions[])
303 {
304     tLevel::const_iterator candidate = level.lower_bound(name);
305     while (candidate != level.end()) {
306         const TString& candidateName = (*candidate).first;
307         TString::size_type parenAt = candidateName.find_first_of('(');
308         if (parenAt != candidateName.npos && candidateName.compare(0, parenAt, name) == 0) {
309             TSymbol* symbol = candidate->second;
310             symbol->setExtensions(num, extensions);
311         } else
312             break;
313         ++candidate;
314     }
315 }
316
317 //
318 // Make all symbols in this table level read only.
319 //
320 void TSymbolTableLevel::readOnly()
321 {
322     for (tLevel::iterator it = level.begin(); it != level.end(); ++it)
323         (*it).second->makeReadOnly();
324 }
325
326 //
327 // Copy a symbol, but the copy is writable; call readOnly() afterward if that's not desired.
328 //
329 TSymbol::TSymbol(const TSymbol& copyOf)
330 {
331     name = NewPoolTString(copyOf.name->c_str());
332     uniqueId = copyOf.uniqueId;
333     writable = true;
334 }
335
336 TVariable::TVariable(const TVariable& copyOf) : TSymbol(copyOf)
337 {
338     type.deepCopy(copyOf.type);
339     userType = copyOf.userType;
340
341     // we don't support specialization-constant subtrees in cloned tables, only extensions
342     constSubtree = nullptr;
343     extensions = nullptr;
344     memberExtensions = nullptr;
345     if (copyOf.getNumExtensions() > 0)
346         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
347     if (copyOf.hasMemberExtensions()) {
348         for (int m = 0; m < (int)copyOf.type.getStruct()->size(); ++m) {
349             if (copyOf.getNumMemberExtensions(m) > 0)
350                 setMemberExtensions(m, copyOf.getNumMemberExtensions(m), copyOf.getMemberExtensions(m));
351         }
352     }
353
354     if (! copyOf.constArray.empty()) {
355         assert(! copyOf.type.isStruct());
356         TConstUnionArray newArray(copyOf.constArray, 0, copyOf.constArray.size());
357         constArray = newArray;
358     }
359 }
360
361 TVariable* TVariable::clone() const
362 {
363     TVariable *variable = new TVariable(*this);
364
365     return variable;
366 }
367
368 TFunction::TFunction(const TFunction& copyOf) : TSymbol(copyOf)
369 {
370     for (unsigned int i = 0; i < copyOf.parameters.size(); ++i) {
371         TParameter param;
372         parameters.push_back(param);
373         parameters.back().copyParam(copyOf.parameters[i]);
374     }
375
376     extensions = nullptr;
377     if (copyOf.getNumExtensions() > 0)
378         setExtensions(copyOf.getNumExtensions(), copyOf.getExtensions());
379     returnType.deepCopy(copyOf.returnType);
380     mangledName = copyOf.mangledName;
381     op = copyOf.op;
382     defined = copyOf.defined;
383     prototyped = copyOf.prototyped;
384     implicitThis = copyOf.implicitThis;
385     illegalImplicitThis = copyOf.illegalImplicitThis;
386     defaultParamCount = copyOf.defaultParamCount;
387 }
388
389 TFunction* TFunction::clone() const
390 {
391     TFunction *function = new TFunction(*this);
392
393     return function;
394 }
395
396 TAnonMember* TAnonMember::clone() const
397 {
398     // Anonymous members of a given block should be cloned at a higher level,
399     // where they can all be assured to still end up pointing to a single
400     // copy of the original container.
401     assert(0);
402
403     return 0;
404 }
405
406 TSymbolTableLevel* TSymbolTableLevel::clone() const
407 {
408     TSymbolTableLevel *symTableLevel = new TSymbolTableLevel();
409     symTableLevel->anonId = anonId;
410     symTableLevel->thisLevel = thisLevel;
411     std::vector<bool> containerCopied(anonId, false);
412     tLevel::const_iterator iter;
413     for (iter = level.begin(); iter != level.end(); ++iter) {
414         const TAnonMember* anon = iter->second->getAsAnonMember();
415         if (anon) {
416             // Insert all the anonymous members of this same container at once,
417             // avoid inserting the remaining members in the future, once this has been done,
418             // allowing them to all be part of the same new container.
419             if (! containerCopied[anon->getAnonId()]) {
420                 TVariable* container = anon->getAnonContainer().clone();
421                 container->changeName(NewPoolTString(""));
422                 // insert the container and all its members
423                 symTableLevel->insert(*container, false);
424                 containerCopied[anon->getAnonId()] = true;
425             }
426         } else
427             symTableLevel->insert(*iter->second->clone(), false);
428     }
429
430     return symTableLevel;
431 }
432
433 void TSymbolTable::copyTable(const TSymbolTable& copyOf)
434 {
435     assert(adoptedLevels == copyOf.adoptedLevels);
436
437     uniqueId = copyOf.uniqueId;
438     noBuiltInRedeclarations = copyOf.noBuiltInRedeclarations;
439     separateNameSpaces = copyOf.separateNameSpaces;
440     for (unsigned int i = copyOf.adoptedLevels; i < copyOf.table.size(); ++i)
441         table.push_back(copyOf.table[i]->clone());
442 }
443
444 } // end namespace glslang