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