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