Nonfunctional: fix a typo.
[platform/upstream/glslang.git] / glslang / MachineIndependent / ParseHelper.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 #include "ParseHelper.h"
38 #include "Scan.h"
39
40 #include "osinclude.h"
41 #include <stdarg.h>
42 #include <algorithm>
43
44 #include "preprocessor/PpContext.h"
45
46 extern int yyparse(glslang::TParseContext*);
47
48 namespace glslang {
49
50 TParseContext::TParseContext(TSymbolTable& symt, TIntermediate& interm, bool pb, int v, EProfile p, EShLanguage L, TInfoSink& is,
51                              bool fc, EShMessages m) :
52             intermediate(interm), symbolTable(symt), infoSink(is), language(L),
53             version(v), profile(p), forwardCompatible(fc), messages(m),
54             contextPragma(true, false), loopNestingLevel(0), controlFlowNestingLevel(0), structNestingLevel(0),
55             tokensBeforeEOF(false), limits(resources.limits), currentScanner(0),
56             numErrors(0), parsingBuiltins(pb), afterEOF(false),
57             atomicUintOffsets(0), anyIndexLimits(false)
58 {
59     // ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
60     linkage = new TIntermAggregate;
61
62     // set all precision defaults to EpqNone, which is correct for all desktop types
63     // and for ES types that don't have defaults (thus getting an error on use)
64     for (int type = 0; type < EbtNumTypes; ++type)
65         defaultPrecision[type] = EpqNone;
66
67     for (int type = 0; type < maxSamplerIndex; ++type)
68         defaultSamplerPrecision[type] = EpqNone;
69
70     // replace with real defaults for those that have them
71     if (profile == EEsProfile) {
72         TSampler sampler;
73         sampler.set(EbtFloat, Esd2D);
74         defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
75         sampler.set(EbtFloat, EsdCube);
76         defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
77         sampler.set(EbtFloat, Esd2D);
78         sampler.external = true;
79         defaultSamplerPrecision[computeSamplerTypeIndex(sampler)] = EpqLow;
80
81         switch (language) {
82         case EShLangFragment:
83             defaultPrecision[EbtInt] = EpqMedium;
84             defaultPrecision[EbtUint] = EpqMedium;
85             break;
86         default:
87             defaultPrecision[EbtInt] = EpqHigh;
88             defaultPrecision[EbtUint] = EpqHigh;
89             defaultPrecision[EbtFloat] = EpqHigh;
90             break;
91         }
92
93         defaultPrecision[EbtSampler] = EpqLow;
94         defaultPrecision[EbtAtomicUint] = EpqHigh;
95     }
96
97     globalUniformDefaults.clear();
98     globalUniformDefaults.layoutMatrix = ElmColumnMajor;
99     globalUniformDefaults.layoutPacking = ElpShared;
100
101     globalBufferDefaults.clear();
102     globalBufferDefaults.layoutMatrix = ElmColumnMajor;
103     globalBufferDefaults.layoutPacking = ElpShared;
104
105     globalInputDefaults.clear();
106     globalOutputDefaults.clear();
107
108     // "Shaders in the transform 
109     // feedback capturing mode have an initial global default of
110     //     layout(xfb_buffer = 0) out;"
111     if (language == EShLangVertex ||
112         language == EShLangTessControl ||
113         language == EShLangTessEvaluation ||
114         language == EShLangGeometry)
115         globalOutputDefaults.layoutXfbBuffer = 0;
116
117     if (language == EShLangGeometry)
118         globalOutputDefaults.layoutStream = 0;
119 }
120
121 TParseContext::~TParseContext()
122 {
123     delete [] atomicUintOffsets;
124 }
125
126 void TParseContext::setLimits(const TBuiltInResource& r)
127 {
128     resources = r;
129
130     anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
131                      ! limits.generalConstantMatrixVectorIndexing ||
132                      ! limits.generalSamplerIndexing ||
133                      ! limits.generalUniformIndexing ||
134                      ! limits.generalVariableIndexing ||
135                      ! limits.generalVaryingIndexing;
136
137     intermediate.setLimits(resources);
138
139     // "Each binding point tracks its own current default offset for
140     // inheritance of subsequent variables using the same binding. The initial state of compilation is that all
141     // binding points have an offset of 0."
142     atomicUintOffsets = new int[resources.maxAtomicCounterBindings];
143     for (int b = 0; b < resources.maxAtomicCounterBindings; ++b)
144         atomicUintOffsets[b] = 0;
145 }
146
147 //
148 // Parse an array of strings using yyparse, going through the
149 // preprocessor to tokenize the shader strings, then through
150 // the GLSL scanner.
151 //
152 // Returns true for successful acceptance of the shader, false if any errors.
153 //
154 bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
155 {
156     currentScanner = &input;
157     ppContext.setInput(input, versionWillBeError);
158     yyparse(this);
159     finalErrorCheck();
160
161     return numErrors == 0;
162 }
163
164 // This is called from bison when it has a parse (syntax) error
165 void TParseContext::parserError(const char* s)
166 {
167     if (afterEOF) {
168         if (tokensBeforeEOF == 1)
169             error(getCurrentLoc(), "", "pre-mature EOF", s, "");
170     } else
171         error(getCurrentLoc(), "", "", s, "");
172 }
173
174 void TParseContext::handlePragma(TSourceLoc loc, const TVector<TString>& tokens)
175 {
176     if (tokens.size() == 0)
177         return;
178
179     if (tokens[0].compare("optimize") == 0) {
180         if (tokens.size() != 4) {
181             error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
182             return;
183         }
184
185         if (tokens[1].compare("(") != 0) {
186             error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
187             return;
188         }
189
190         if (tokens[2].compare("on") == 0)
191             contextPragma.optimize = true;
192         else if (tokens[2].compare("off") == 0)
193             contextPragma.optimize = false;
194         else {
195             error(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
196             return;
197         }
198
199         if (tokens[3].compare(")") != 0) {
200             error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
201             return;
202         }
203     } else if (tokens[0].compare("debug") == 0) {
204         if (tokens.size() != 4) {
205             error(loc, "debug pragma syntax is incorrect", "#pragma", "");
206             return;
207         }
208
209         if (tokens[1].compare("(") != 0) {
210             error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
211             return;
212         }
213
214         if (tokens[2].compare("on") == 0)
215             contextPragma.debug = true;
216         else if (tokens[2].compare("off") == 0)
217             contextPragma.debug = false;
218         else {
219             error(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
220             return;
221         }
222
223         if (tokens[3].compare(")") != 0) {
224             error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
225             return;
226         }
227     }
228 }
229
230 ///////////////////////////////////////////////////////////////////////
231 //
232 // Sub- vector and matrix fields
233 //
234 ////////////////////////////////////////////////////////////////////////
235
236 //
237 // Look at a '.' field selector string and change it into offsets
238 // for a vector or scalar
239 //
240 // Returns true if there is no error.
241 //
242 bool TParseContext::parseVectorFields(TSourceLoc loc, const TString& compString, int vecSize, TVectorFields& fields)
243 {
244     fields.num = (int) compString.size();
245     if (fields.num > 4) {
246         error(loc, "illegal vector field selection", compString.c_str(), "");
247         return false;
248     }
249
250     enum {
251         exyzw,
252         ergba,
253         estpq,
254     } fieldSet[4];
255
256     for (int i = 0; i < fields.num; ++i) {
257         switch (compString[i])  {
258         case 'x':
259             fields.offsets[i] = 0;
260             fieldSet[i] = exyzw;
261             break;
262         case 'r':
263             fields.offsets[i] = 0;
264             fieldSet[i] = ergba;
265             break;
266         case 's':
267             fields.offsets[i] = 0;
268             fieldSet[i] = estpq;
269             break;
270         case 'y':
271             fields.offsets[i] = 1;
272             fieldSet[i] = exyzw;
273             break;
274         case 'g':
275             fields.offsets[i] = 1;
276             fieldSet[i] = ergba;
277             break;
278         case 't':
279             fields.offsets[i] = 1;
280             fieldSet[i] = estpq;
281             break;
282         case 'z':
283             fields.offsets[i] = 2;
284             fieldSet[i] = exyzw;
285             break;
286         case 'b':
287             fields.offsets[i] = 2;
288             fieldSet[i] = ergba;
289             break;
290         case 'p':
291             fields.offsets[i] = 2;
292             fieldSet[i] = estpq;
293             break;
294
295         case 'w':
296             fields.offsets[i] = 3;
297             fieldSet[i] = exyzw;
298             break;
299         case 'a':
300             fields.offsets[i] = 3;
301             fieldSet[i] = ergba;
302             break;
303         case 'q':
304             fields.offsets[i] = 3;
305             fieldSet[i] = estpq;
306             break;
307         default:
308             error(loc, "illegal vector field selection", compString.c_str(), "");
309             return false;
310         }
311     }
312
313     for (int i = 0; i < fields.num; ++i) {
314         if (fields.offsets[i] >= vecSize) {
315             error(loc, "vector field selection out of range",  compString.c_str(), "");
316             return false;
317         }
318
319         if (i > 0) {
320             if (fieldSet[i] != fieldSet[i-1]) {
321                 error(loc, "illegal - vector component fields not from the same set", compString.c_str(), "");
322                 return false;
323             }
324         }
325     }
326
327     return true;
328 }
329
330 ///////////////////////////////////////////////////////////////////////
331 //
332 // Errors
333 //
334 ////////////////////////////////////////////////////////////////////////
335
336 //
337 // Used to output syntax, parsing, and semantic errors.
338 //
339 void C_DECL TParseContext::error(TSourceLoc loc, const char* szReason, const char* szToken,
340                                  const char* szExtraInfoFormat, ...)
341 {
342     const int maxSize = GlslangMaxTokenLength + 200;
343     char szExtraInfo[maxSize];
344     va_list marker;
345
346     va_start(marker, szExtraInfoFormat);
347
348     safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, marker);
349
350     infoSink.info.prefix(EPrefixError);
351     infoSink.info.location(loc);
352     infoSink.info << "'" << szToken <<  "' : " << szReason << " " << szExtraInfo << "\n";
353
354     va_end(marker);
355
356     ++numErrors;
357 }
358
359 void C_DECL TParseContext::warn(TSourceLoc loc, const char* szReason, const char* szToken,
360                                  const char* szExtraInfoFormat, ...)
361 {
362     if (messages & EShMsgSuppressWarnings)
363         return;
364
365     const int maxSize = GlslangMaxTokenLength + 200;
366     char szExtraInfo[maxSize];
367     va_list marker;
368
369     va_start(marker, szExtraInfoFormat);
370
371     safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, marker);
372
373     infoSink.info.prefix(EPrefixWarning);
374     infoSink.info.location(loc);
375     infoSink.info << "'" << szToken <<  "' : " << szReason << " " << szExtraInfo << "\n";
376
377     va_end(marker);
378 }
379
380 //
381 // Handle seeing a variable identifier in the grammar.
382 //
383 TIntermTyped* TParseContext::handleVariable(TSourceLoc loc, TSymbol* symbol, TString* string)
384 {
385     TIntermTyped* node = 0;
386
387     // Error check for function requiring specific extensions present.
388     if (symbol && symbol->getNumExtensions())
389         requireExtensions(loc, symbol->getNumExtensions(), symbol->getExtensions(), symbol->getName().c_str());
390
391     if (symbol && symbol->isReadOnly()) {
392         // All shared things containing an implicitly sized array must be copied up 
393         // on first use, so that all future references will share its array structure,
394         // so that editing the implicit size will effect all nodes consuming it,
395         // and so that editing the implicit size won't change the shared one.
396         //
397         // If this is a variable or a block, check it and all it contains, but if this 
398         // is a member of an anonymous block, check the whole block, as the whole block
399         // will need to be copied up if it contains an implicitly-sized array.
400         if (symbol->getType().containsImplicitlySizedArray() || (symbol->getAsAnonMember() && symbol->getAsAnonMember()->getAnonContainer().getType().containsImplicitlySizedArray()))
401             makeEditable(symbol);
402     }
403
404     const TVariable* variable;
405     const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : 0;
406     if (anon) {
407         // It was a member of an anonymous container.
408
409         // Create a subtree for its dereference.
410         variable = anon->getAnonContainer().getAsVariable();
411         TIntermTyped* container = intermediate.addSymbol(*variable, loc);
412         TIntermTyped* constNode = intermediate.addConstantUnion(anon->getMemberNumber(), loc);
413         node = intermediate.addIndex(EOpIndexDirectStruct, container, constNode, loc);
414
415         node->setType(*(*variable->getType().getStruct())[anon->getMemberNumber()].type);
416         if (node->getType().hiddenMember())
417             error(loc, "member of nameless block was not redeclared", string->c_str(), "");
418     } else {
419         // Not a member of an anonymous container.
420
421         // The symbol table search was done in the lexical phase.
422         // See if it was a variable.
423         variable = symbol ? symbol->getAsVariable() : 0;
424         if (symbol && ! variable)
425             error(loc, "variable name expected", string->c_str(), "");
426
427         // Recovery, if it wasn't found or was not a variable.
428         if (! variable)
429             variable = new TVariable(string, TType(EbtVoid));
430
431         if (variable->getType().getQualifier().storage == EvqConst)
432             node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
433         else
434             node = intermediate.addSymbol(*variable, loc);
435     }
436
437     if (variable->getType().getQualifier().isIo())
438         intermediate.addIoAccessed(*string);
439
440     return node;
441 }
442
443 //
444 // Handle seeing a base[index] dereference in the grammar.
445 //
446 TIntermTyped* TParseContext::handleBracketDereference(TSourceLoc loc, TIntermTyped* base, TIntermTyped* index)
447 {
448     TIntermTyped* result = 0;
449
450     int indexValue = 0;
451     if (index->getQualifier().storage == EvqConst) {
452         indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
453         checkIndex(loc, base->getType(), indexValue);
454     }
455
456     variableCheck(base);
457     if (! base->isArray() && ! base->isMatrix() && ! base->isVector()) {
458         if (base->getAsSymbolNode())
459             error(loc, " left of '[' is not of type array, matrix, or vector ", base->getAsSymbolNode()->getName().c_str(), "");
460         else
461             error(loc, " left of '[' is not of type array, matrix, or vector ", "expression", "");
462     } else if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
463         return intermediate.foldDereference(base, indexValue, loc);
464     else {
465         // at least one of base and index is variable...
466
467         if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
468             handleIoResizeArrayAccess(loc, base);
469
470         if (index->getQualifier().storage == EvqConst) {
471             if (base->getType().isImplicitlySizedArray())
472                 updateImplicitArraySize(loc, base, indexValue);
473             result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
474         } else {
475             if (base->getType().isImplicitlySizedArray()) {
476                 if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
477                     error(loc, "", "[", "array must be sized by a redeclaration or layout qualifier before being indexed with a variable");
478                 else
479                     error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
480             }
481             if (base->getBasicType() == EbtBlock)
482                 requireProfile(base->getLoc(), ~EEsProfile, "variable indexing block array");
483             else if (language == EShLangFragment && base->getQualifier().isPipeOutput())
484                 requireProfile(base->getLoc(), ~EEsProfile, "variable indexing fragment shader ouput array");
485             else if (base->getBasicType() == EbtSampler && version >= 130) {
486                 const char* explanation = "variable indexing sampler array";
487                 requireProfile(base->getLoc(), ECoreProfile | ECompatibilityProfile, explanation);
488                 profileRequires(base->getLoc(), ECoreProfile | ECompatibilityProfile, 400, 0, explanation);
489             }
490
491             result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
492         }
493     }
494
495     if (result == 0) {
496         // Insert dummy error-recovery result
497         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
498     } else {
499         // Insert valid dereferenced result
500         TType newType(base->getType(), 0);  // dereferenced type
501         if (base->getType().getQualifier().storage == EvqConst && index->getQualifier().storage == EvqConst)
502             newType.getQualifier().storage = EvqConst;
503         else
504             newType.getQualifier().storage = EvqTemporary;
505         result->setType(newType);
506
507         if (anyIndexLimits)
508             handleIndexLimits(loc, base, index);
509     }
510
511     return result;
512 }
513
514 void TParseContext::checkIndex(TSourceLoc loc, const TType& type, int& index)
515 {
516     if (index < 0) {
517         error(loc, "", "[", "index out of range '%d'", index);
518         index = 0;
519     } else if (type.isArray()) {
520         if (type.isExplicitlySizedArray() && index >= type.getArraySize()) {
521             error(loc, "", "[", "array index out of range '%d'", index);
522             index = type.getArraySize() - 1;
523         }
524     } else if (type.isVector()) {
525         if (index >= type.getVectorSize()) {
526             error(loc, "", "[", "vector index out of range '%d'", index);
527             index = type.getVectorSize() - 1;
528         }
529     } else if (type.isMatrix()) {
530         if (index >= type.getMatrixCols()) {
531             error(loc, "", "[", "matrix index out of range '%d'", index);
532             index = type.getMatrixCols() - 1;
533         }
534     }           
535 }
536
537 // for ES 2.0 (version 100) limitations for almost all index operations except vertex-shader uniforms
538 void TParseContext::handleIndexLimits(TSourceLoc loc, TIntermTyped* base, TIntermTyped* index)
539 {
540     if ((! limits.generalSamplerIndexing && base->getBasicType() == EbtSampler) ||
541         (! limits.generalUniformIndexing && base->getQualifier().isUniformOrBuffer() && language != EShLangVertex) ||
542         (! limits.generalAttributeMatrixVectorIndexing && base->getQualifier().isPipeInput() && language == EShLangVertex && (base->getType().isMatrix() || base->getType().isVector())) ||
543         (! limits.generalConstantMatrixVectorIndexing && base->getAsConstantUnion()) ||
544         (! limits.generalVariableIndexing && ! base->getType().getQualifier().isUniformOrBuffer() &&
545                                              ! base->getType().getQualifier().isPipeInput() &&
546                                              ! base->getType().getQualifier().isPipeOutput() &&
547                                                base->getType().getQualifier().storage != EvqConst) ||
548         (! limits.generalVaryingIndexing && (base->getType().getQualifier().isPipeInput() ||
549                                                 base->getType().getQualifier().isPipeOutput()))) {
550         // it's too early to know what the inductive variables are, save it for post processing
551         needsIndexLimitationChecking.push_back(index);
552     }
553 }
554
555 // Make a shared symbol have a non-shared version that can be edited by the current 
556 // compile, such that editing its type will not change the shared version and will
557 // effect all nodes sharing it.
558 void TParseContext::makeEditable(TSymbol*& symbol)
559 {
560     // copyUp() does a deep copy of the type.
561     symbol = symbolTable.copyUp(symbol);
562
563     // Also, see if it's tied to IO resizing
564     if (isIoResizeArray(symbol->getType()))
565         ioArraySymbolResizeList.push_back(symbol);
566
567     // Also, save it in the AST for linker use.
568     intermediate.addSymbolLinkageNode(linkage, *symbol);
569 }
570
571 // Return true if this is a geometry shader input array or tessellation control output array.
572 bool TParseContext::isIoResizeArray(const TType& type) const
573 {
574     return type.isArray() &&
575            ((language == EShLangGeometry    && type.getQualifier().storage == EvqVaryingIn) ||
576             (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch));
577 }
578
579 // If an array is not isIoResizeArray() but is an io array, make sure it has the right size
580 void TParseContext::fixIoArraySize(TSourceLoc loc, TType& type)
581 {
582     if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
583         return;
584
585     assert(! isIoResizeArray(type));
586
587     if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
588         return;
589
590     if (language == EShLangTessControl || language == EShLangTessEvaluation) {
591         if (type.getArraySize() != resources.maxPatchVertices) {
592             if (type.isExplicitlySizedArray())
593                 error(loc, "tessellation input array size must be gl_MaxPatchVertices or implicitly sized", "[]", "");
594             type.changeArraySize(resources.maxPatchVertices);
595         }
596     }
597 }
598
599 // Issue any errors if the non-array object is missing arrayness WRT
600 // shader I/O that has array requirements.
601 // All arrayness checking is handled in array paths, this is for 
602 void TParseContext::ioArrayCheck(TSourceLoc loc, const TType& type, const TString& identifier)
603 {
604     if (! type.isArray() && ! symbolTable.atBuiltInLevel()) {
605         if (type.getQualifier().isArrayedIo(language))
606             error(loc, "type must be an array:", type.getStorageQualifierString(), identifier.c_str());
607     }
608 }
609
610 // Handle a dereference of a geometry shader input array or tessellation control output array.
611 // See ioArraySymbolResizeList comment in ParseHelper.h.
612 //
613 void TParseContext::handleIoResizeArrayAccess(TSourceLoc loc, TIntermTyped* base)
614 {
615     TIntermSymbol* symbolNode = base->getAsSymbolNode();
616     assert(symbolNode);
617     if (! symbolNode)
618         return;
619
620     // fix array size, if it can be fixed and needs to be fixed (will allow variable indexing)
621     if (symbolNode->getType().isImplicitlySizedArray()) {
622         int newSize = getIoArrayImplicitSize();
623         if (newSize)
624             symbolNode->getWritableType().changeArraySize(newSize);
625     }
626 }
627
628 // If there has been an input primitive declaration (geometry shader) or an output
629 // number of vertices declaration(tessellation shader), make sure all input array types
630 // match it in size.  Types come either from nodes in the AST or symbols in the 
631 // symbol table.
632 //
633 // Types without an array size will be given one.
634 // Types already having a size that is wrong will get an error.
635 //
636 void TParseContext::checkIoArraysConsistency(TSourceLoc loc, bool tailOnly)
637 {
638     int requiredSize = getIoArrayImplicitSize();
639     if (requiredSize == 0)
640         return;
641
642     const char* feature;
643     if (language == EShLangGeometry)
644         feature = TQualifier::getGeometryString(intermediate.getInputPrimitive());
645     else if (language == EShLangTessControl)
646         feature = "vertices";
647
648     if (tailOnly) {
649         checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName());
650         return;
651     }
652
653     for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i)
654         checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName());
655 }
656
657 int TParseContext::getIoArrayImplicitSize() const
658 {
659     if (language == EShLangGeometry)
660         return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
661     else if (language == EShLangTessControl)
662         return intermediate.getVertices();
663     else
664         return 0;
665 }
666
667 void TParseContext::checkIoArrayConsistency(TSourceLoc loc, int requiredSize, const char* feature, TType& type, const TString& name)
668 {
669     if (type.isImplicitlySizedArray())
670         type.changeArraySize(requiredSize);
671     else if (type.getArraySize() != requiredSize) {
672         if (language == EShLangGeometry)
673             error(loc, "inconsistent input primitive for array size of", feature, name.c_str());
674         else if (language == EShLangTessControl)
675             error(loc, "inconsistent output number of vertices for array size of", feature, name.c_str());
676         else
677             assert(0);
678     }
679 }
680
681 // Handle seeing a binary node with a math operation.
682 TIntermTyped* TParseContext::handleBinaryMath(TSourceLoc loc, const char* str, TOperator op, TIntermTyped* left, TIntermTyped* right)
683 {
684     rValueErrorCheck(loc, str, left->getAsTyped());
685     rValueErrorCheck(loc, str, right->getAsTyped());
686
687     TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
688     if (! result)
689         binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
690
691     return result;
692 }
693
694 // Handle seeing a unary node with a math operation.
695 TIntermTyped* TParseContext::handleUnaryMath(TSourceLoc loc, const char* str, TOperator op, TIntermTyped* childNode)
696 {
697     rValueErrorCheck(loc, str, childNode);
698
699     TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
700
701     if (result)
702         return result;
703     else
704         unaryOpError(loc, str, childNode->getCompleteString());
705         
706     return childNode;
707 }
708
709 //
710 // Handle seeing a base.field dereference in the grammar.
711 //
712 TIntermTyped* TParseContext::handleDotDereference(TSourceLoc loc, TIntermTyped* base, TString& field)
713 {
714     variableCheck(base);
715
716     //
717     // .length() can't be resolved until we later see the function-calling syntax.
718     // Save away the name in the AST for now.  Processing is compeleted in 
719     // handleLengthMethod().
720     //
721     if (field == "length") {
722         if (base->isArray()) {
723             profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, ".length");
724             profileRequires(loc, EEsProfile, 300, 0, ".length");
725         } else if (base->isVector() || base->isMatrix()) {
726             const char* feature = ".length() on vectors and matrices";
727             requireProfile(loc, ~EEsProfile, feature);
728             profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, feature);
729         } else {
730             error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString().c_str());
731
732             return base;
733         }
734
735         return intermediate.addMethod(base, TType(EbtInt), &field, loc);
736     }
737
738     // It's not .length() if we get to here.
739
740     if (base->isArray()) {
741         error(loc, "cannot apply to an array:", ".", field.c_str());
742
743         return base;
744     }
745
746     // It's neither an array nor .length() if we get here,
747     // leaving swizzles and struct/block dereferences.
748
749     TIntermTyped* result = base;
750     if (base->isVector() || base->isScalar()) {
751         if (base->isScalar()) {
752             const char* dotFeature = "scalar swizzle";
753             requireProfile(loc, ~EEsProfile, dotFeature);
754             profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, dotFeature);
755         }
756
757         TVectorFields fields;
758         if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) {
759             fields.num = 1;
760             fields.offsets[0] = 0;
761         }
762
763         if (base->isScalar()) {
764             if (fields.num == 1)
765                 return result;
766             else {
767                 TType type(base->getBasicType(), EvqTemporary, fields.num);
768                 return addConstructor(loc, base, type, mapTypeToConstructorOp(type));
769             }
770         }
771
772         if (base->getType().getQualifier().storage == EvqConst)
773             result = intermediate.foldSwizzle(base, fields, loc);
774         else {
775             if (fields.num == 1) {
776                 TIntermTyped* index = intermediate.addConstantUnion(fields.offsets[0], loc);
777                 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
778                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision));
779             } else {
780                 TString vectorString = field;
781                 TIntermTyped* index = intermediate.addSwizzle(fields, loc);
782                 result = intermediate.addIndex(EOpVectorSwizzle, base, index, loc);
783                 result->setType(TType(base->getBasicType(), EvqTemporary, base->getType().getQualifier().precision, (int) vectorString.size()));
784             }
785         }
786     } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
787         const TTypeList* fields = base->getType().getStruct();
788         bool fieldFound = false;
789         int member;
790         for (member = 0; member < (int)fields->size(); ++member) {
791             if ((*fields)[member].type->getFieldName() == field) {
792                 fieldFound = true;
793                 break;
794             }
795         }
796         if (fieldFound) {
797             if (base->getType().getQualifier().storage == EvqConst)
798                 result = intermediate.foldDereference(base, member, loc);
799             else {
800                 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
801                 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
802                 result->setType(*(*fields)[member].type);
803             }
804         } else
805             error(loc, "no such field in structure", field.c_str(), "");
806     } else
807         error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
808
809     return result;
810 }
811
812 //
813 // Handle seeing a function declarator in the grammar.  This is the precursor
814 // to recognizing a function prototype or function definition.
815 //
816 TFunction* TParseContext::handleFunctionDeclarator(TSourceLoc loc, TFunction& function, bool prototype)
817 {
818     // ES can't declare prototypes inside functions
819     if (! symbolTable.atGlobalLevel())
820         requireProfile(loc, ~EEsProfile, "local function declaration");
821
822     //
823     // Multiple declarations of the same function name are allowed.
824     //
825     // If this is a definition, the definition production code will check for redefinitions
826     // (we don't know at this point if it's a definition or not).
827     //
828     // Redeclarations (full signature match) are allowed.  But, return types and parameter qualifiers must also match.
829     //  - except ES 100, which only allows a single prototype
830     //
831     // ES 100 does not allow redefining, but does allow overloading of built-in functions.
832     // ES 300 does not allow redefining or overloading of built-in functions.
833     //
834     bool builtIn;
835     TSymbol* symbol = symbolTable.find(function.getMangledName(), &builtIn);
836     if (symbol && symbol->getAsFunction() && builtIn)
837         requireProfile(loc, ~EEsProfile, "redefinition of built-in function");
838     const TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
839     if (prevDec) {
840         if (prevDec->isPrototyped() && prototype)
841             profileRequires(loc, EEsProfile, 300, 0, "multiple prototypes for same function");
842         if (prevDec->getType() != function.getType())
843             error(loc, "overloaded functions must have the same return type", function.getType().getBasicTypeString().c_str(), "");
844         for (int i = 0; i < prevDec->getParamCount(); ++i) {
845             if ((*prevDec)[i].type->getQualifier().storage != function[i].type->getQualifier().storage)
846                 error(loc, "overloaded functions must have the same parameter storage qualifiers for argument", function[i].type->getStorageQualifierString(), "%d", i+1);
847
848             if ((*prevDec)[i].type->getQualifier().precision != function[i].type->getQualifier().precision)
849                 error(loc, "overloaded functions must have the same parameter precision qualifiers for argument", function[i].type->getPrecisionQualifierString(), "%d", i+1);
850         }
851     }
852
853     arrayObjectCheck(loc, function.getType(), "array in function return type");
854
855     if (prototype) {
856         // All built-in functions are defined, even though they don't have a body.
857         // Count their prototype as a definition instead.
858         if (symbolTable.atBuiltInLevel())
859             function.setDefined();
860         else {
861             if (prevDec && ! builtIn)                
862                 symbol->getAsFunction()->setPrototyped();  // need a writable one, but like having prevDec as a const
863             function.setPrototyped();
864         }
865     }
866
867     // This insert won't actually insert it if it's a duplicate signature, but it will still check for
868     // other forms of name collisions.
869     if (! symbolTable.insert(function))
870         error(loc, "function name is redeclaration of existing name", function.getName().c_str(), "");
871
872     //
873     // If this is a redeclaration, it could also be a definition,
874     // in which case, we need to use the parameter names from this one, and not the one that's
875     // being redeclared.  So, pass back this declaration, not the one in the symbol table.
876     //
877     return &function;
878 }
879
880 //
881 // Handle seeing the function prototype in front of a function definition in the grammar.  
882 // The body is handled after this function returns.
883 //
884 TIntermAggregate* TParseContext::handleFunctionDefinition(TSourceLoc loc, TFunction& function)
885 {
886     currentCaller = function.getMangledName();
887     TSymbol* symbol = symbolTable.find(function.getMangledName());
888     TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
889
890     if (! prevDec)
891         error(loc, "can't find function", function.getName().c_str(), "");
892     // Note:  'prevDec' could be 'function' if this is the first time we've seen function
893     // as it would have just been put in the symbol table.  Otherwise, we're looking up
894     // an earlier occurance.
895
896     if (prevDec && prevDec->isDefined()) {
897         // Then this function already has a body.
898         error(loc, "function already has a body", function.getName().c_str(), "");
899     }
900     if (prevDec && ! prevDec->isDefined()) {
901         prevDec->setDefined();
902
903         // Remember the return type for later checking for RETURN statements.
904         currentFunctionType = &(prevDec->getType());
905     } else
906         currentFunctionType = new TType(EbtVoid);
907     functionReturnsValue = false;
908
909     //
910     // Raise error message if main function takes any parameters or returns anything other than void
911     //
912     if (function.getName() == "main") {
913         if (function.getParamCount() > 0)
914             error(loc, "function cannot take any parameter(s)", function.getName().c_str(), "");
915         if (function.getType().getBasicType() != EbtVoid)
916             error(loc, "", function.getType().getBasicTypeString().c_str(), "main function cannot return a value");
917         intermediate.addMainCount();
918     }
919
920     //
921     // New symbol table scope for body of function plus its arguments
922     //
923     symbolTable.push();
924
925     //
926     // Insert parameters into the symbol table.
927     // If the parameter has no name, it's not an error, just don't insert it
928     // (could be used for unused args).
929     //
930     // Also, accumulate the list of parameters into the HIL, so lower level code
931     // knows where to find parameters.
932     //
933     TIntermAggregate* paramNodes = new TIntermAggregate;
934     for (int i = 0; i < function.getParamCount(); i++) {
935         TParameter& param = function[i];
936         if (param.name != 0) {
937             TVariable *variable = new TVariable(param.name, *param.type);
938
939             // Insert the parameters with name in the symbol table.
940             if (! symbolTable.insert(*variable))
941                 error(loc, "redefinition", variable->getName().c_str(), "");
942             else {
943                 // Transfer ownership of name pointer to symbol table.
944                 param.name = 0;
945
946                 // Add the parameter to the HIL
947                 paramNodes = intermediate.growAggregate(paramNodes,
948                                                         intermediate.addSymbol(*variable, loc),
949                                                         loc);
950             }
951         } else
952             paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(0, "", *param.type, loc), loc);
953     }
954     intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
955     loopNestingLevel = 0;
956     controlFlowNestingLevel = 0;
957
958     return paramNodes;
959 }
960
961 //
962 // Handle seeing function call syntax in the grammar, which could be any of
963 //  - .length() method
964 //  - constructor
965 //  - a call to a built-in function mapped to an operator
966 //  - a call to a built-in function that will remain a function call (e.g., texturing)
967 //  - user function
968 //  - subroutine call (not implemented yet)
969 //
970 TIntermTyped* TParseContext::handleFunctionCall(TSourceLoc loc, TFunction* function, TIntermNode* arguments)
971 {
972     TIntermTyped* result = 0;
973
974     TOperator op = function->getBuiltInOp();
975     if (op == EOpArrayLength)
976         result = handleLengthMethod(loc, function, arguments);
977     else if (op != EOpNull) {
978         //
979         // Then this should be a constructor.
980         // Don't go through the symbol table for constructors.
981         // Their parameters will be verified algorithmically.
982         //
983         TType type(EbtVoid);  // use this to get the type back
984         if (! constructorError(loc, arguments, *function, op, type)) {
985             //
986             // It's a constructor, of type 'type'.
987             //
988             result = addConstructor(loc, arguments, type, op);
989             if (result == 0)
990                 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
991         }
992     } else {
993         //
994         // Find it in the symbol table.
995         //
996         const TFunction* fnCandidate;
997         bool builtIn;
998         fnCandidate = findFunction(loc, *function, builtIn);
999         if (fnCandidate) {
1000             // This is a declared function that might map to
1001             //  - a built-in operator,
1002             //  - a built-in function not mapped to an operator, or
1003             //  - a user function.
1004
1005             // Error check for a function requiring specific extensions present.
1006             if (builtIn && fnCandidate->getNumExtensions())
1007                 requireExtensions(loc, fnCandidate->getNumExtensions(), fnCandidate->getExtensions(), fnCandidate->getName().c_str());
1008
1009             if (arguments) {
1010                 // Make sure qualifications work for these arguments.
1011                 TIntermAggregate* aggregate = arguments->getAsAggregate();
1012                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1013                     // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1014                     // is the single argument itself or its children are the arguments.  Only one argument
1015                     // means take 'arguments' itself as the one argument.
1016                     TIntermNode* arg = fnCandidate->getParamCount() == 1 ? arguments : (aggregate ? aggregate->getSequence()[i] : arguments);
1017                     TQualifier& formalQualifier = (*fnCandidate)[i].type->getQualifier();
1018                     if (formalQualifier.storage == EvqOut || formalQualifier.storage == EvqInOut) {
1019                         if (lValueErrorCheck(arguments->getLoc(), "assign", arg->getAsTyped()))
1020                             error(arguments->getLoc(), "Non-L-value cannot be passed for 'out' or 'inout' parameters.", "out", "");
1021                     }
1022                     TQualifier& argQualifier = arg->getAsTyped()->getQualifier();
1023                     if (argQualifier.isMemory()) {
1024                         const char* message = "argument cannot drop memory qualifier when passed to formal parameter";
1025                         if (argQualifier.volatil && ! formalQualifier.volatil)
1026                             error(arguments->getLoc(), message, "volatile", "");
1027                         if (argQualifier.coherent && ! formalQualifier.coherent)
1028                             error(arguments->getLoc(), message, "coherent", "");
1029                         if (argQualifier.restrict && ! formalQualifier.restrict)
1030                             error(arguments->getLoc(), message, "restrict", "");
1031                         if (argQualifier.readonly && ! formalQualifier.readonly)
1032                             error(arguments->getLoc(), message, "readonly", "");
1033                         if (argQualifier.writeonly && ! formalQualifier.writeonly)
1034                             error(arguments->getLoc(), message, "writeonly", "");
1035                     }
1036                     // TODO 4.5 functionality:  A shader will fail to compile 
1037                     // if the value passed to the memargument of an atomic memory function does not correspond to a buffer or
1038                     // shared variable. It is acceptable to pass an element of an array or a single component of a vector to the 
1039                     // memargument of an atomic memory function, as long as the underlying array or vector is a buffer or 
1040                     // shared variable.
1041                 }
1042
1043                 // Convert 'in' arguments
1044                 addInputArgumentConversions(*fnCandidate, arguments);  // arguments may be modified if it's just a single argument node
1045             }
1046
1047             op = fnCandidate->getBuiltInOp();
1048             if (builtIn && op != EOpNull) {
1049                 // A function call mapped to a built-in operation.
1050                 result = intermediate.addBuiltInFunctionCall(loc, op, fnCandidate->getParamCount() == 1, arguments, fnCandidate->getType());
1051                 if (result == 0)  {
1052                     error(arguments->getLoc(), " wrong operand type", "Internal Error",
1053                                         "built in unary operator function.  Type: %s",
1054                                         static_cast<TIntermTyped*>(arguments)->getCompleteString().c_str());
1055                 }
1056             } else {
1057                 // This is a function call not mapped to built-in operator, but it could still be a built-in function
1058                 result = intermediate.setAggregateOperator(arguments, EOpFunctionCall, fnCandidate->getType(), loc);
1059                 TIntermAggregate* call = result->getAsAggregate();
1060                 call->setName(fnCandidate->getMangledName());
1061
1062                 // this is how we know whether the given function is a built-in function or a user-defined function
1063                 // if builtIn == false, it's a userDefined -> could be an overloaded built-in function also
1064                 // if builtIn == true, it's definitely a built-in function with EOpNull
1065                 if (! builtIn) {
1066                     call->setUserDefined();
1067                     intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1068                 }
1069
1070                 if (builtIn)
1071                     nonOpBuiltInCheck(loc, *fnCandidate, *call);
1072             }
1073
1074             // Convert 'out' arguments.  If it was a constant folded built-in, it won't be an aggregate anymore.
1075             // Built-ins with a single argument aren't called with an aggregate, but they also don't have an output.
1076             // Also, build the qualifier list for user function calls, which are always called with an aggregate.
1077             if (result->getAsAggregate()) {
1078                 TQualifierList& qualifierList = result->getAsAggregate()->getQualifierList();
1079                 for (int i = 0; i < fnCandidate->getParamCount(); ++i) {
1080                     TStorageQualifier qual = (*fnCandidate)[i].type->getQualifier().storage;
1081                     qualifierList.push_back(qual);
1082                 }
1083                 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1084             }
1085         }
1086     }
1087
1088     // generic error recovery
1089     // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1090     if (result == 0)
1091         result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
1092
1093     return result;
1094 }
1095
1096 // Finish processing object.length(). This started earlier in handleDotDereference(), where
1097 // the ".length" part was recognized and semantically checked, and finished here where the 
1098 // function syntax "()" is recognized.
1099 //
1100 // Return resulting tree node.
1101 TIntermTyped* TParseContext::handleLengthMethod(TSourceLoc loc, TFunction* function, TIntermNode* intermNode)
1102 {
1103     int length = 0;
1104
1105     if (function->getParamCount() > 0)
1106         error(loc, "method does not accept any arguments", function->getName().c_str(), "");
1107     else {
1108         const TType& type = intermNode->getAsTyped()->getType();
1109         if (type.isArray()) {
1110             if (type.isRuntimeSizedArray()) {
1111                 // Create a unary op and let the back end handle it
1112                 return intermediate.addBuiltInFunctionCall(loc, EOpArrayLength, true, intermNode, TType(EbtInt));
1113             } else if (type.isImplicitlySizedArray()) {
1114                 if (intermNode->getAsSymbolNode() && isIoResizeArray(type)) {
1115                     // We could be between a layout declaration that gives a built-in io array implicit size and 
1116                     // a user redeclaration of that array, meaning we have to substitute its implicit size here 
1117                     // without actually redeclaring the array.  (It is an error to use a member before the
1118                     // redeclaration, but not an error to use the array name itself.)
1119                     const TString& name = intermNode->getAsSymbolNode()->getName();
1120                     if (name == "gl_in" || name == "gl_out")
1121                         length = getIoArrayImplicitSize();
1122                 }
1123                 if (length == 0) {
1124                     if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1125                         error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1126                     else
1127                         error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1128                 }
1129             } else
1130                 length = type.getArraySize();
1131         } else if (type.isMatrix())
1132             length = type.getMatrixCols();
1133         else if (type.isVector())
1134             length = type.getVectorSize();
1135         else {
1136             // we should not get here, because earlier semantic checking should have prevented this path
1137             error(loc, ".length()", "unexpected use of .length()", "");
1138         }
1139     }
1140
1141     if (length == 0)
1142         length = 1;
1143
1144     return intermediate.addConstantUnion(length, loc);
1145 }
1146
1147 //
1148 // Add any needed implicit conversions for function-call arguments to input parameters.
1149 //
1150 void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1151 {
1152     TIntermAggregate* aggregate = arguments->getAsAggregate();
1153
1154     // Process each argument's conversion
1155     for (int i = 0; i < function.getParamCount(); ++i) {
1156         // At this early point there is a slight ambiguity between whether an aggregate 'arguments'
1157         // is the single argument itself or its children are the arguments.  Only one argument
1158         // means take 'arguments' itself as the one argument.
1159         TIntermTyped* arg = function.getParamCount() == 1 ? arguments->getAsTyped() : (aggregate ? aggregate->getSequence()[i]->getAsTyped() : arguments->getAsTyped());
1160         if (*function[i].type != arg->getType()) {
1161             if (function[i].type->getQualifier().isParamInput()) {
1162                 // In-qualified arguments just need an extra node added above the argument to
1163                 // convert to the correct type.
1164                 arg = intermediate.addConversion(EOpFunctionCall, *function[i].type, arg);
1165                 if (arg) {
1166                     if (aggregate)
1167                         aggregate->getSequence()[i] = arg;
1168                     else
1169                         arguments = arg;
1170                 }
1171             }
1172         }
1173     }
1174 }
1175
1176 //
1177 // Add any needed implicit output conversions for function-call arguments.  This
1178 // can require a new tree topology, complicated further by whether the function
1179 // has a return value.
1180 //
1181 // Returns a node of a subtree that evaluates to the return value of the function.
1182 //
1183 TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1184 {
1185     TIntermSequence& arguments = intermNode.getSequence();
1186
1187     // Will there be any output conversions?
1188     bool outputConversions = false;
1189     for (int i = 0; i < function.getParamCount(); ++i) {
1190         if (*function[i].type != arguments[i]->getAsTyped()->getType() && function[i].type->getQualifier().storage == EvqOut) {
1191             outputConversions = true;
1192             break;
1193         }
1194     }
1195
1196     if (! outputConversions)
1197         return &intermNode;
1198
1199     // Setup for the new tree, if needed:
1200     //
1201     // Output conversions need a different tree topology.
1202     // Out-qualified arguments need a temporary of the correct type, with the call
1203     // followed by an assignment of the temporary to the original argument:
1204     //     void: function(arg, ...)  ->        (          function(tempArg, ...), arg = tempArg, ...)
1205     //     ret = function(arg, ...)  ->  ret = (tempRet = function(tempArg, ...), arg = tempArg, ..., tempRet)
1206     // Where the "tempArg" type needs no conversion as an argument, but will convert on assignment.
1207     TIntermTyped* conversionTree = 0;
1208     TVariable* tempRet = 0;
1209     if (intermNode.getBasicType() != EbtVoid) {
1210         // do the "tempRet = function(...), " bit from above
1211         tempRet = makeInternalVariable("tempReturn", intermNode.getType());
1212         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1213         conversionTree = intermediate.addAssign(EOpAssign, tempRetNode, &intermNode, intermNode.getLoc());
1214     } else
1215         conversionTree = &intermNode;
1216
1217     conversionTree = intermediate.makeAggregate(conversionTree);
1218
1219     // Process each argument's conversion
1220     for (int i = 0; i < function.getParamCount(); ++i) {
1221         if (*function[i].type != arguments[i]->getAsTyped()->getType()) {
1222             if (function[i].type->getQualifier().isParamOutput()) {
1223                 // Out-qualified arguments need to use the topology set up above.
1224                 // do the " ...(tempArg, ...), arg = tempArg" bit from above
1225                 TVariable* tempArg = makeInternalVariable("tempArg", *function[i].type);
1226                 tempArg->getWritableType().getQualifier().makeTemporary();
1227                 TIntermSymbol* tempArgNode = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1228                 TIntermTyped* tempAssign = intermediate.addAssign(EOpAssign, arguments[i]->getAsTyped(), tempArgNode, arguments[i]->getLoc());
1229                 conversionTree = intermediate.growAggregate(conversionTree, tempAssign, arguments[i]->getLoc());
1230                 // replace the argument with another node for the same tempArg variable
1231                 arguments[i] = intermediate.addSymbol(*tempArg, intermNode.getLoc());
1232             }
1233         }
1234     }
1235
1236     // Finalize the tree topology (see bigger comment above).
1237     if (tempRet) {
1238         // do the "..., tempRet" bit from above
1239         TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1240         conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1241     }
1242     conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1243
1244     return conversionTree;
1245 }
1246
1247 //
1248 // Do additional checking of built-in function calls that were not mapped
1249 // to built-in operations (e.g., texturing functions).
1250 //
1251 // Assumes there has been a semantically correct match to a built-in function.
1252 //
1253 void TParseContext::nonOpBuiltInCheck(TSourceLoc loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
1254 {
1255     // built-in texturing functions get their return value precision from the precision of the sampler
1256     if (fnCandidate.getType().getQualifier().precision == EpqNone &&
1257         fnCandidate.getParamCount() > 0 && fnCandidate[0].type->getBasicType() == EbtSampler)
1258         callNode.getQualifier().precision = callNode.getAsAggregate()->getSequence()[0]->getAsTyped()->getQualifier().precision;
1259
1260     if (fnCandidate.getName().compare(0, 7, "texture") == 0) {
1261         if (fnCandidate.getName().compare(0, 13, "textureGather") == 0) {
1262             TString featureString = fnCandidate.getName() + "(...)";
1263             const char* feature = featureString.c_str();
1264             profileRequires(loc, EEsProfile, 310, 0, feature);
1265
1266             int compArg = -1;  // track which argument, if any, is the constant component argument
1267             if (fnCandidate.getName().compare("textureGatherOffset") == 0) {
1268                 // GL_ARB_texture_gather is good enough for 2D non-shadow textures with no component argument
1269                 if (fnCandidate[0].type->getSampler().dim == Esd2D && ! fnCandidate[0].type->getSampler().shadow && fnCandidate.getParamCount() == 3)
1270                     profileRequires(loc, ~EEsProfile, 400, GL_ARB_texture_gather, feature);
1271                 else
1272                     profileRequires(loc, ~EEsProfile, 400, GL_ARB_gpu_shader5, feature);
1273                 if (! fnCandidate[0].type->getSampler().shadow)
1274                     compArg = 3;
1275             } else if (fnCandidate.getName().compare("textureGatherOffsets") == 0) {
1276                 profileRequires(loc, ~EEsProfile, 400, GL_ARB_gpu_shader5, feature);
1277                 if (! fnCandidate[0].type->getSampler().shadow)
1278                     compArg = 3;
1279                 // check for constant offsets
1280                 int offsetArg = fnCandidate[0].type->getSampler().shadow ? 3 : 2;
1281                 if (! callNode.getSequence()[offsetArg]->getAsConstantUnion())
1282                     error(loc, "must be a compile-time constant:", feature, "offsets argument");
1283             } else if (fnCandidate.getName().compare("textureGather") == 0) {
1284                 // More than two arguments needs gpu_shader5, and rectangular or shadow needs gpu_shader5,
1285                 // otherwise, need GL_ARB_texture_gather.
1286                 if (fnCandidate.getParamCount() > 2 || fnCandidate[0].type->getSampler().dim == EsdRect || fnCandidate[0].type->getSampler().shadow) {
1287                     profileRequires(loc, ~EEsProfile, 400, GL_ARB_gpu_shader5, feature);
1288                     if (! fnCandidate[0].type->getSampler().shadow)
1289                         compArg = 2;
1290                 } else
1291                     profileRequires(loc, ~EEsProfile, 400, GL_ARB_texture_gather, feature);
1292             }
1293
1294             if (compArg > 0 && compArg < fnCandidate.getParamCount()) {
1295                 if (callNode.getSequence()[compArg]->getAsConstantUnion()) {
1296                     int value = callNode.getSequence()[compArg]->getAsConstantUnion()->getConstArray()[0].getIConst();
1297                     if (value < 0 || value > 3)
1298                         error(loc, "must be 0, 1, 2, or 3:", feature, "component argument");
1299                 } else
1300                     error(loc, "must be a compile-time constant:", feature, "component argument");
1301             }
1302         } else {
1303             // this is only for functions not starting "textureGather"...
1304             if (fnCandidate.getName().find("Offset") != TString::npos) {
1305
1306                 // Handle texture-offset limits checking
1307                 int arg = -1;
1308                 if (fnCandidate.getName().compare("textureOffset") == 0)
1309                     arg = 2;
1310                 else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
1311                     arg = 3;
1312                 else if (fnCandidate.getName().compare("textureProjOffset") == 0)
1313                     arg = 2;
1314                 else if (fnCandidate.getName().compare("textureLodOffset") == 0)
1315                     arg = 3;
1316                 else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
1317                     arg = 3;
1318                 else if (fnCandidate.getName().compare("textureGradOffset") == 0)
1319                     arg = 4;
1320                 else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
1321                     arg = 4;
1322
1323                 if (arg > 0) {
1324                     if (! callNode.getSequence()[arg]->getAsConstantUnion())
1325                         error(loc, "argument must be compile-time constant", "texel offset", "");
1326                     else {
1327                         const TType& type = callNode.getSequence()[arg]->getAsTyped()->getType();
1328                         for (int c = 0; c < type.getVectorSize(); ++c) {
1329                             int offset = callNode.getSequence()[arg]->getAsConstantUnion()->getConstArray()[c].getIConst();
1330                             if (offset > resources.maxProgramTexelOffset || offset < resources.minProgramTexelOffset)
1331                                 error(loc, "value is out of range:", "texel offset", "[gl_MinProgramTexelOffset, gl_MaxProgramTexelOffset]");
1332                         }
1333                     }
1334                 }
1335             }
1336         }
1337     }
1338
1339     // GL_ARB_shader_texture_image_samples
1340     if (fnCandidate.getName().compare(0, 14, "textureSamples") == 0 || fnCandidate.getName().compare(0, 12, "imageSamples") == 0)
1341         profileRequires(loc, ~EEsProfile, 450, GL_ARB_shader_texture_image_samples, "textureSamples and imageSamples");
1342
1343     if (fnCandidate.getName().compare(0, 11, "imageAtomic") == 0) {
1344         const TType& imageType = callNode.getSequence()[0]->getAsTyped()->getType();
1345         if (imageType.getSampler().type == EbtInt || imageType.getSampler().type == EbtUint) {
1346             if (imageType.getQualifier().layoutFormat != ElfR32i && imageType.getQualifier().layoutFormat != ElfR32ui)
1347                 error(loc, "only supported on image with format r32i or r32ui", fnCandidate.getName().c_str(), "");
1348         } else if (fnCandidate.getName().compare(0, 19, "imageAtomicExchange") != 0) 
1349             error(loc, "only supported on integer images", fnCandidate.getName().c_str(), "");
1350     }
1351 }
1352
1353 //
1354 // Handle seeing a built-in constructor in a grammar production.
1355 //
1356 TFunction* TParseContext::handleConstructorCall(TSourceLoc loc, const TPublicType& publicType)
1357 {
1358     TType type(publicType);
1359     type.getQualifier().precision = EpqNone;
1360
1361     if (type.isArray()) {
1362         profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "arrayed constructor");
1363         profileRequires(loc, EEsProfile, 300, 0, "arrayed constructor");
1364     }
1365
1366     TOperator op = mapTypeToConstructorOp(type);
1367
1368     if (op == EOpNull) {
1369         error(loc, "cannot construct this type", type.getBasicString(), "");
1370         op = EOpConstructFloat;
1371         TType errorType(EbtFloat);
1372         type.shallowCopy(errorType);
1373     }
1374
1375     TString empty("");
1376
1377     return new TFunction(&empty, type, op);
1378 }
1379
1380 //
1381 // Given a type, find what operation would fully construct it.
1382 //
1383 TOperator TParseContext::mapTypeToConstructorOp(const TType& type) const
1384 {
1385     if (type.isStruct())
1386         return EOpConstructStruct;
1387
1388     TOperator op;
1389     switch (type.getBasicType()) {
1390     case EbtFloat:
1391         if (type.isMatrix()) {
1392             switch (type.getMatrixCols()) {
1393             case 2:
1394                 switch (type.getMatrixRows()) {
1395                 case 2: op = EOpConstructMat2x2; break;
1396                 case 3: op = EOpConstructMat2x3; break;
1397                 case 4: op = EOpConstructMat2x4; break;
1398                 default: break; // some compilers want this
1399                 }
1400                 break;
1401             case 3:
1402                 switch (type.getMatrixRows()) {
1403                 case 2: op = EOpConstructMat3x2; break;
1404                 case 3: op = EOpConstructMat3x3; break;
1405                 case 4: op = EOpConstructMat3x4; break;
1406                 default: break; // some compilers want this
1407                 }
1408                 break;
1409             case 4:
1410                 switch (type.getMatrixRows()) {
1411                 case 2: op = EOpConstructMat4x2; break;
1412                 case 3: op = EOpConstructMat4x3; break;
1413                 case 4: op = EOpConstructMat4x4; break;
1414                 default: break; // some compilers want this
1415                 }
1416                 break;
1417             default: break; // some compilers want this
1418             }
1419         } else {
1420             switch(type.getVectorSize()) {
1421             case 1: op = EOpConstructFloat; break;
1422             case 2: op = EOpConstructVec2;  break;
1423             case 3: op = EOpConstructVec3;  break;
1424             case 4: op = EOpConstructVec4;  break;
1425             default: break; // some compilers want this
1426             }
1427         }
1428         break;
1429     case EbtDouble:
1430         if (type.getMatrixCols()) {
1431             switch (type.getMatrixCols()) {
1432             case 2:
1433                 switch (type.getMatrixRows()) {
1434                 case 2: op = EOpConstructDMat2x2; break;
1435                 case 3: op = EOpConstructDMat2x3; break;
1436                 case 4: op = EOpConstructDMat2x4; break;
1437                 default: break; // some compilers want this
1438                 }
1439                 break;
1440             case 3:
1441                 switch (type.getMatrixRows()) {
1442                 case 2: op = EOpConstructDMat3x2; break;
1443                 case 3: op = EOpConstructDMat3x3; break;
1444                 case 4: op = EOpConstructDMat3x4; break;
1445                 default: break; // some compilers want this
1446                 }
1447                 break;
1448             case 4:
1449                 switch (type.getMatrixRows()) {
1450                 case 2: op = EOpConstructDMat4x2; break;
1451                 case 3: op = EOpConstructDMat4x3; break;
1452                 case 4: op = EOpConstructDMat4x4; break;
1453                 default: break; // some compilers want this
1454                 }
1455                 break;
1456             }
1457         } else {
1458             switch(type.getVectorSize()) {
1459             case 1: op = EOpConstructDouble; break;
1460             case 2: op = EOpConstructDVec2;  break;
1461             case 3: op = EOpConstructDVec3;  break;
1462             case 4: op = EOpConstructDVec4;  break;
1463             default: break; // some compilers want this
1464             }
1465         }
1466         break;
1467     case EbtInt:
1468         switch(type.getVectorSize()) {
1469         case 1: op = EOpConstructInt;   break;
1470         case 2: op = EOpConstructIVec2; break;
1471         case 3: op = EOpConstructIVec3; break;
1472         case 4: op = EOpConstructIVec4; break;
1473         default: break; // some compilers want this
1474         }
1475         break;
1476     case EbtUint:
1477         switch(type.getVectorSize()) {
1478         case 1: op = EOpConstructUint;  break;
1479         case 2: op = EOpConstructUVec2; break;
1480         case 3: op = EOpConstructUVec3; break;
1481         case 4: op = EOpConstructUVec4; break;
1482         default: break; // some compilers want this
1483         }
1484         break;
1485     case EbtBool:
1486         switch(type.getVectorSize()) {
1487         case 1:  op = EOpConstructBool;  break;
1488         case 2:  op = EOpConstructBVec2; break;
1489         case 3:  op = EOpConstructBVec3; break;
1490         case 4:  op = EOpConstructBVec4; break;
1491         default: break; // some compilers want this
1492         }
1493         break;
1494     default:
1495         op = EOpNull;
1496         break;
1497     }
1498
1499     return op;
1500 }
1501
1502 //
1503 // Same error message for all places assignments don't work.
1504 //
1505 void TParseContext::assignError(TSourceLoc loc, const char* op, TString left, TString right)
1506 {
1507     error(loc, "", op, "cannot convert from '%s' to '%s'",
1508           right.c_str(), left.c_str());
1509 }
1510
1511 //
1512 // Same error message for all places unary operations don't work.
1513 //
1514 void TParseContext::unaryOpError(TSourceLoc loc, const char* op, TString operand)
1515 {
1516    error(loc, " wrong operand type", op,
1517           "no operation '%s' exists that takes an operand of type %s (or there is no acceptable conversion)",
1518           op, operand.c_str());
1519 }
1520
1521 //
1522 // Same error message for all binary operations don't work.
1523 //
1524 void TParseContext::binaryOpError(TSourceLoc loc, const char* op, TString left, TString right)
1525 {
1526     error(loc, " wrong operand types:", op,
1527             "no operation '%s' exists that takes a left-hand operand of type '%s' and "
1528             "a right operand of type '%s' (or there is no acceptable conversion)",
1529             op, left.c_str(), right.c_str());
1530 }
1531
1532 //
1533 // A basic type of EbtVoid is a key that the name string was seen in the source, but
1534 // it was not found as a variable in the symbol table.  If so, give the error
1535 // message and insert a dummy variable in the symbol table to prevent future errors.
1536 //
1537 void TParseContext::variableCheck(TIntermTyped*& nodePtr)
1538 {
1539     TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
1540     if (! symbol)
1541         return;
1542
1543     if (symbol->getType().getBasicType() == EbtVoid) {
1544         error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
1545
1546         // Add to symbol table to prevent future error messages on the same name
1547
1548         TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
1549         symbolTable.insert(*fakeVariable);
1550
1551         // substitute a symbol node for this new variable
1552         nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
1553     } else {
1554         switch (symbol->getQualifier().storage) {
1555         case EvqPointCoord:
1556             profileRequires(symbol->getLoc(), ENoProfile, 120, 0, "gl_PointCoord");
1557             break;
1558         default: break; // some compilers want this
1559         }
1560     }
1561 }
1562
1563 //
1564 // Both test and if necessary, spit out an error, to see if the node is really
1565 // an l-value that can be operated on this way.
1566 //
1567 // Returns true if the was an error.
1568 //
1569 bool TParseContext::lValueErrorCheck(TSourceLoc loc, const char* op, TIntermTyped* node)
1570 {
1571     TIntermBinary* binaryNode = node->getAsBinaryNode();
1572
1573     if (binaryNode) {
1574         bool errorReturn;
1575
1576         switch(binaryNode->getOp()) {
1577         case EOpIndexDirect:
1578         case EOpIndexIndirect:
1579         case EOpIndexDirectStruct:
1580             return lValueErrorCheck(loc, op, binaryNode->getLeft());
1581         case EOpVectorSwizzle:
1582             errorReturn = lValueErrorCheck(loc, op, binaryNode->getLeft());
1583             if (!errorReturn) {
1584                 int offset[4] = {0,0,0,0};
1585
1586                 TIntermTyped* rightNode = binaryNode->getRight();
1587                 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
1588
1589                 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
1590                                                p != aggrNode->getSequence().end(); p++) {
1591                     int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
1592                     offset[value]++;
1593                     if (offset[value] > 1) {
1594                         error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
1595
1596                         return true;
1597                     }
1598                 }
1599             }
1600
1601             return errorReturn;
1602         default:
1603             break;
1604         }
1605         error(loc, " l-value required", op, "", "");
1606
1607         return true;
1608     }
1609
1610
1611     const char* symbol = 0;
1612     TIntermSymbol* symNode = node->getAsSymbolNode();
1613     if (symNode != 0)
1614         symbol = symNode->getName().c_str();
1615
1616     const char* message = 0;
1617     switch (node->getQualifier().storage) {
1618     case EvqConst:          message = "can't modify a const";        break;
1619     case EvqConstReadOnly:  message = "can't modify a const";        break;
1620     case EvqVaryingIn:      message = "can't modify shader input";   break;
1621     case EvqInstanceId:     message = "can't modify gl_InstanceID";  break;
1622     case EvqVertexId:       message = "can't modify gl_VertexID";    break;
1623     case EvqFace:           message = "can't modify gl_FrontFace";   break;
1624     case EvqFragCoord:      message = "can't modify gl_FragCoord";   break;
1625     case EvqPointCoord:     message = "can't modify gl_PointCoord";  break;
1626     case EvqUniform:        message = "can't modify a uniform";      break;
1627     case EvqBuffer:
1628         if (node->getQualifier().readonly)
1629             message = "can't modify a readonly buffer";
1630         break;
1631     default:
1632
1633         //
1634         // Type that can't be written to?
1635         //
1636         switch (node->getBasicType()) {
1637         case EbtSampler:
1638             message = "can't modify a sampler";
1639             break;
1640         case EbtAtomicUint:
1641             message = "can't modify an atomic_uint";
1642             break;
1643         case EbtVoid:
1644             message = "can't modify void";
1645             break;
1646         default:
1647             break;
1648         }
1649     }
1650
1651     if (message == 0 && binaryNode == 0 && symNode == 0) {
1652         error(loc, " l-value required", op, "", "");
1653
1654         return true;
1655     }
1656
1657
1658     //
1659     // Everything else is okay, no error.
1660     //
1661     if (message == 0)
1662         return false;
1663
1664     //
1665     // If we get here, we have an error and a message.
1666     //
1667     if (symNode)
1668         error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
1669     else
1670         error(loc, " l-value required", op, "(%s)", message);
1671
1672     return true;
1673 }
1674
1675 // Test for and give an error if the node can't be read from.
1676 void TParseContext::rValueErrorCheck(TSourceLoc loc, const char* op, TIntermTyped* node)
1677 {
1678     if (! node)
1679         return;
1680
1681     TIntermBinary* binaryNode = node->getAsBinaryNode();
1682     if (binaryNode) {
1683         switch(binaryNode->getOp()) {
1684         case EOpIndexDirect:
1685         case EOpIndexIndirect:
1686         case EOpIndexDirectStruct:
1687         case EOpVectorSwizzle:
1688             rValueErrorCheck(loc, op, binaryNode->getLeft());
1689         default:
1690             break;
1691         }
1692
1693         return;
1694     }
1695
1696     TIntermSymbol* symNode = node->getAsSymbolNode();
1697     if (symNode && symNode->getQualifier().writeonly)
1698         error(loc, "can't read from writeonly object: ", op, symNode->getName().c_str());
1699 }
1700
1701 //
1702 // Both test, and if necessary spit out an error, to see if the node is really
1703 // a constant.
1704 //
1705 void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
1706 {
1707     if (node->getQualifier().storage != EvqConst)
1708         error(node->getLoc(), "constant expression required", token, "");
1709 }
1710
1711 //
1712 // Both test, and if necessary spit out an error, to see if the node is really
1713 // an integer.
1714 //
1715 void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
1716 {
1717     if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
1718         return;
1719
1720     error(node->getLoc(), "scalar integer expression required", token, "");
1721 }
1722
1723 //
1724 // Both test, and if necessary spit out an error, to see if we are currently
1725 // globally scoped.
1726 //
1727 void TParseContext::globalCheck(TSourceLoc loc, const char* token)
1728 {
1729     if (! symbolTable.atGlobalLevel())
1730         error(loc, "not allowed in nested scope", token, "");
1731 }
1732
1733 //
1734 // Reserved errors for GLSL.
1735 //
1736 void TParseContext::reservedErrorCheck(TSourceLoc loc, const TString& identifier)
1737 {
1738     // "Identifiers starting with "gl_" are reserved for use by OpenGL, and may not be
1739     // declared in a shader; this results in a compile-time error."
1740     if (! symbolTable.atBuiltInLevel()) {
1741         if (builtInName(identifier))
1742             error(loc, "identifiers starting with \"gl_\" are reserved", identifier.c_str(), "");
1743
1744         // "In addition, all identifiers containing two consecutive underscores (__) are
1745         // reserved; using such a name does not itself result in an error, but may result
1746         // in undefined behavior."
1747         if (identifier.find("__") != TString::npos)
1748             warn(loc, "identifiers containing consecutive underscores (\"__\") are reserved", identifier.c_str(), "");
1749     }
1750 }
1751
1752 //
1753 // Reserved errors for the preprocessor.
1754 //
1755 void TParseContext::reservedPpErrorCheck(TSourceLoc loc, const char* identifier, const char* op)
1756 {
1757     // "All macro names containing two consecutive underscores ( __ ) are reserved;
1758     // defining such a name does not itself result in an error, but may result in
1759     // undefined behavior.  All macro names prefixed with "GL_" ("GL" followed by a
1760     // single underscore) are also reserved, and defining such a name results in a
1761     // compile-time error."
1762     if (strncmp(identifier, "GL_", 3) == 0)
1763         error(loc, "names beginning with \"GL_\" can't be defined:", op,  identifier);
1764     else if (strstr(identifier, "__") != 0)
1765         warn(loc, "names containing consecutive underscores are reserved:", op, identifier);
1766 }
1767
1768 //
1769 // See if this version/profile allows use of the line-continuation character '\'.
1770 //
1771 // Returns true if a line continuation should be done.
1772 //
1773 bool TParseContext::lineContinuationCheck(TSourceLoc loc, bool endOfComment)
1774 {
1775     const char* message = "line continuation";
1776
1777     bool lineContinuationAllowed = (profile == EEsProfile && version >= 300) ||
1778                                    (profile != EEsProfile && (version >= 420 || extensionsTurnedOn(1, &GL_ARB_shading_language_420pack)));
1779
1780     if (endOfComment) {
1781         if (lineContinuationAllowed)
1782             warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
1783         else
1784             warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
1785
1786         return lineContinuationAllowed;
1787     }
1788
1789     if (messages & EShMsgRelaxedErrors) {
1790         if (! lineContinuationAllowed)
1791             warn(loc, "not allowed in this version", message, "");
1792         return true;
1793     } else {
1794         profileRequires(loc, EEsProfile, 300, 0, message);
1795         profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, message);
1796     }
1797
1798     return lineContinuationAllowed;
1799 }
1800
1801 bool TParseContext::builtInName(const TString& identifier)
1802 {
1803     return identifier.compare(0, 3, "gl_") == 0;
1804 }
1805
1806 //
1807 // Make sure there is enough data and not too many arguments provided to the
1808 // constructor to build something of the type of the constructor.  Also returns
1809 // the type of the constructor.
1810 //
1811 // Returns true if there was an error in construction.
1812 //
1813 bool TParseContext::constructorError(TSourceLoc loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
1814 {
1815     type.shallowCopy(function.getType());
1816
1817     bool constructingMatrix = false;
1818     switch(op) {
1819     case EOpConstructMat2x2:
1820     case EOpConstructMat2x3:
1821     case EOpConstructMat2x4:
1822     case EOpConstructMat3x2:
1823     case EOpConstructMat3x3:
1824     case EOpConstructMat3x4:
1825     case EOpConstructMat4x2:
1826     case EOpConstructMat4x3:
1827     case EOpConstructMat4x4:
1828     case EOpConstructDMat2x2:
1829     case EOpConstructDMat2x3:
1830     case EOpConstructDMat2x4:
1831     case EOpConstructDMat3x2:
1832     case EOpConstructDMat3x3:
1833     case EOpConstructDMat3x4:
1834     case EOpConstructDMat4x2:
1835     case EOpConstructDMat4x3:
1836     case EOpConstructDMat4x4:
1837         constructingMatrix = true;
1838         break;
1839     default:
1840         break;
1841     }
1842
1843     //
1844     // Note: It's okay to have too many components available, but not okay to have unused
1845     // arguments.  'full' will go to true when enough args have been seen.  If we loop
1846     // again, there is an extra argument, so 'overfull' will become true.
1847     //
1848
1849     int size = 0;
1850     bool constType = true;
1851     bool full = false;
1852     bool overFull = false;
1853     bool matrixInMatrix = false;
1854     bool arrayArg = false;
1855     for (int i = 0; i < function.getParamCount(); ++i) {
1856         size += function[i].type->computeNumComponents();
1857
1858         if (constructingMatrix && function[i].type->isMatrix())
1859             matrixInMatrix = true;
1860         if (full)
1861             overFull = true;
1862         if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
1863             full = true;
1864         if (function[i].type->getQualifier().storage != EvqConst)
1865             constType = false;
1866         if (function[i].type->isArray())
1867             arrayArg = true;
1868     }
1869
1870     if (constType)
1871         type.getQualifier().storage = EvqConst;
1872
1873     if (type.isArray()) {
1874         if (type.isImplicitlySizedArray()) {
1875             // auto adapt the constructor type to the number of arguments
1876             type.changeArraySize(function.getParamCount());
1877         } else if (type.getArraySize() != function.getParamCount()) {
1878             error(loc, "array constructor needs one argument per array element", "constructor", "");
1879             return true;
1880         }
1881     }
1882
1883     if (arrayArg && op != EOpConstructStruct) {
1884         error(loc, "constructing from a non-dereferenced array", "constructor", "");
1885         return true;
1886     }
1887
1888     if (matrixInMatrix && ! type.isArray()) {
1889         profileRequires(loc, ENoProfile, 120, 0, "constructing matrix from matrix");
1890
1891         // "If a matrix argument is given to a matrix constructor,
1892         // it is a compile-time error to have any other arguments."
1893         if (function.getParamCount() > 1)
1894             error(loc, "matrix constructed from matrix can only have one argument", "constructor", "");
1895         return false;
1896     }
1897
1898     if (overFull) {
1899         error(loc, "too many arguments", "constructor", "");
1900         return true;
1901     }
1902
1903     if (op == EOpConstructStruct && ! type.isArray() && type.getStruct()->size() != function.getParamCount()) {
1904         error(loc, "Number of constructor parameters does not match the number of structure fields", "constructor", "");
1905         return true;
1906     }
1907
1908     if ((op != EOpConstructStruct && size != 1 && size < type.computeNumComponents()) ||
1909         (op == EOpConstructStruct && size < type.computeNumComponents())) {
1910         error(loc, "not enough data provided for construction", "constructor", "");
1911         return true;
1912     }
1913
1914     TIntermTyped* typed = node->getAsTyped();
1915     if (typed == 0) {
1916         error(loc, "constructor argument does not have a type", "constructor", "");
1917         return true;
1918     }
1919     if (op != EOpConstructStruct && typed->getBasicType() == EbtSampler) {
1920         error(loc, "cannot convert a sampler", "constructor", "");
1921         return true;
1922     }
1923     if (op != EOpConstructStruct && typed->getBasicType() == EbtAtomicUint) {
1924         error(loc, "cannot convert an atomic_uint", "constructor", "");
1925         return true;
1926     }
1927     if (typed->getBasicType() == EbtVoid) {
1928         error(loc, "cannot convert a void", "constructor", "");
1929         return true;
1930     }
1931
1932     return false;
1933 }
1934
1935 // Checks to see if a void variable has been declared and raise an error message for such a case
1936 //
1937 // returns true in case of an error
1938 //
1939 bool TParseContext::voidErrorCheck(TSourceLoc loc, const TString& identifier, const TBasicType basicType)
1940 {
1941     if (basicType == EbtVoid) {
1942         error(loc, "illegal use of type 'void'", identifier.c_str(), "");
1943         return true;
1944     }
1945
1946     return false;
1947 }
1948
1949 // Checks to see if the node (for the expression) contains a scalar boolean expression or not
1950 void TParseContext::boolCheck(TSourceLoc loc, const TIntermTyped* type)
1951 {
1952     if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
1953         error(loc, "boolean expression expected", "", "");
1954 }
1955
1956 // This function checks to see if the node (for the expression) contains a scalar boolean expression or not
1957 void TParseContext::boolCheck(TSourceLoc loc, const TPublicType& pType)
1958 {
1959     if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
1960         error(loc, "boolean expression expected", "", "");
1961 }
1962
1963 void TParseContext::samplerCheck(TSourceLoc loc, const TType& type, const TString& identifier)
1964 {
1965     if (type.getQualifier().storage == EvqUniform)
1966         return;
1967
1968     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtSampler))
1969         error(loc, "non-uniform struct contains a sampler or image:", type.getBasicTypeString().c_str(), identifier.c_str());
1970     else if (type.getBasicType() == EbtSampler && type.getQualifier().storage != EvqUniform)
1971         error(loc, "sampler/image types can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
1972 }
1973
1974 void TParseContext::atomicUintCheck(TSourceLoc loc, const TType& type, const TString& identifier)
1975 {
1976     if (type.getQualifier().storage == EvqUniform)
1977         return;
1978
1979     if (type.getBasicType() == EbtStruct && containsFieldWithBasicType(type, EbtAtomicUint))
1980         error(loc, "non-uniform struct contains an atomic_uint:", type.getBasicTypeString().c_str(), identifier.c_str());
1981     else if (type.getBasicType() == EbtAtomicUint && type.getQualifier().storage != EvqUniform)
1982         error(loc, "atomic_uints can only be used in uniform variables or function parameters:", type.getBasicTypeString().c_str(), identifier.c_str());
1983 }
1984
1985 //
1986 // move from parameter/unknown qualifiers to pipeline in/out qualifiers
1987 //
1988 void TParseContext::pipeInOutFix(TSourceLoc loc, TQualifier& qualifier)
1989 {
1990     switch (qualifier.storage) {
1991     case EvqIn:
1992         profileRequires(loc, ENoProfile, 130, 0, "in for stage inputs");
1993         profileRequires(loc, EEsProfile, 300, 0, "in for stage inputs");
1994         qualifier.storage = EvqVaryingIn;
1995         break;
1996     case EvqOut:
1997         profileRequires(loc, ENoProfile, 130, 0, "out for stage outputs");
1998         profileRequires(loc, EEsProfile, 300, 0, "out for stage outputs");
1999         qualifier.storage = EvqVaryingOut;
2000         break;
2001     case EvqInOut:
2002         qualifier.storage = EvqVaryingIn;
2003         error(loc, "cannot use 'inout' at global scope", "", "");
2004         break;
2005     default:
2006         break;
2007     }
2008 }
2009
2010 void TParseContext::globalQualifierCheck(TSourceLoc loc, const TQualifier& qualifier, const TPublicType& publicType)
2011 {
2012     if (! symbolTable.atGlobalLevel())
2013         return;
2014
2015     if (qualifier.isMemory() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer)
2016         error(loc, "memory qualifiers cannot be used on this type", "", "");
2017
2018     if (qualifier.storage == EvqBuffer && publicType.basicType != EbtBlock)
2019         error(loc, "buffers can be declared only as blocks", "buffer", "");
2020
2021     if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
2022         return;
2023
2024     // now, knowing it is a shader in/out, do all the in/out semantic checks
2025
2026     if (publicType.basicType == EbtBool) {
2027         error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
2028         return;
2029     }
2030
2031     if (publicType.basicType == EbtInt || publicType.basicType == EbtUint || publicType.basicType == EbtDouble) {
2032         profileRequires(loc, EEsProfile, 300, 0, "shader input/output");
2033         if (! qualifier.flat) {
2034             if (qualifier.storage == EvqVaryingIn && language == EShLangFragment)
2035                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
2036             else if (qualifier.storage == EvqVaryingOut && language == EShLangVertex && version == 300)
2037                 error(loc, "must be qualified as flat", TType::getBasicString(publicType.basicType), GetStorageQualifierString(qualifier.storage));
2038         }
2039     }
2040
2041     if (qualifier.patch && qualifier.isInterpolation())
2042         error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
2043
2044     if (qualifier.storage == EvqVaryingIn) {
2045         switch (language) {
2046         case EShLangVertex:
2047             if (publicType.basicType == EbtStruct) {
2048                 error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), "");
2049                 return;
2050             }
2051             if (publicType.arraySizes) {
2052                 requireProfile(loc, ~EEsProfile, "vertex input arrays");
2053                 profileRequires(loc, ENoProfile, 150, 0, "vertex input arrays");
2054             }
2055             if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
2056                 error(loc, "vertex input cannot be further qualified", "", "");
2057             break;
2058
2059         case EShLangTessControl:
2060             if (qualifier.patch)
2061                 error(loc, "can only use on output in tessellation-control shader", "patch", "");
2062             break;
2063
2064         case EShLangTessEvaluation:
2065             break;
2066
2067         case EShLangGeometry:
2068             break;
2069
2070         case EShLangFragment:
2071             if (publicType.userDef) {
2072                 profileRequires(loc, EEsProfile, 300, 0, "fragment-shader struct input");
2073                 profileRequires(loc, ~EEsProfile, 150, 0, "fragment-shader struct input");
2074             }
2075             break;
2076
2077         case EShLangCompute:
2078             if (! symbolTable.atBuiltInLevel())
2079                 error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
2080             break;
2081
2082         default:
2083             break;
2084         }
2085     } else {
2086         // qualifier.storage == EvqVaryingOut
2087         switch (language) {
2088         case EShLangVertex:
2089             if (publicType.userDef) {
2090                 profileRequires(loc, EEsProfile, 300, 0, "vertex-shader struct output");
2091                 profileRequires(loc, ~EEsProfile, 150, 0, "vertex-shader struct output");
2092             }
2093             break;
2094
2095         case EShLangTessControl:
2096             break;
2097
2098         case EShLangTessEvaluation:
2099             if (qualifier.patch)
2100                 error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
2101             break;
2102
2103         case EShLangGeometry:
2104             break;
2105
2106         case EShLangFragment:
2107             profileRequires(loc, EEsProfile, 300, 0, "fragment shader output");
2108             if (publicType.basicType == EbtStruct) {
2109                 error(loc, "cannot be a structure", GetStorageQualifierString(qualifier.storage), "");
2110                 return;
2111             }
2112             if (publicType.matrixRows > 0) {
2113                 error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
2114                 return;
2115             }
2116         break;
2117
2118         case EShLangCompute:
2119             error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
2120             break;
2121
2122         default:
2123             break;
2124         }
2125     }
2126 }
2127
2128 //
2129 // Merge characteristics of the 'src' qualifier into the 'dst'.
2130 // If there is duplication, issue error messages, unless 'force'
2131 // is specified, which means to just override default settings.
2132 //
2133 // Also, when force is false, it will be assumed that 'src' follows
2134 // 'dst', for the purpose of error checking order for versions
2135 // that require specific orderings of qualifiers.
2136 //
2137 void TParseContext::mergeQualifiers(TSourceLoc loc, TQualifier& dst, const TQualifier& src, bool force)
2138 {
2139     // Multiple auxiliary qualifiers (mostly done later by 'individual qualifiers')
2140     if (src.isAuxiliary() && dst.isAuxiliary())
2141         error(loc, "can only have one auxiliary qualifier (centroid, patch, and sample)", "", "");
2142
2143     // Multiple interpolation qualifiers (mostly done later by 'individual qualifiers')
2144     if (src.isInterpolation() && dst.isInterpolation())
2145         error(loc, "can only have one interpolation qualifier (flat, smooth, noperspective)", "", "");
2146
2147     // Ordering
2148     if (! force && ((profile != EEsProfile && version < 420) || 
2149                      profile == EEsProfile && version < 310)
2150                 && ! extensionsTurnedOn(1, &GL_ARB_shading_language_420pack)) {
2151         // non-function parameters
2152         if (src.invariant && (dst.isInterpolation() || dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
2153             error(loc, "invariant qualifier must appear first", "", "");
2154         else if (src.isInterpolation() && (dst.isAuxiliary() || dst.storage != EvqTemporary || dst.precision != EpqNone))
2155             error(loc, "interpolation qualifiers must appear before storage and precision qualifiers", "", "");
2156         else if (src.isAuxiliary() && (dst.storage != EvqTemporary || dst.precision != EpqNone))
2157             error(loc, "Auxiliary qualifiers (centroid, patch, and sample) must appear before storage and precision qualifiers", "", "");
2158         else if (src.storage != EvqTemporary && (dst.precision != EpqNone))
2159             error(loc, "precision qualifier must appear as last qualifier", "", "");
2160
2161         // function parameters
2162         if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
2163             error(loc, "in/out must appear before const", "", "");
2164     }
2165
2166     // Storage qualification
2167     if (dst.storage == EvqTemporary || dst.storage == EvqGlobal)
2168         dst.storage = src.storage;
2169     else if ((dst.storage == EvqIn  && src.storage == EvqOut) ||
2170              (dst.storage == EvqOut && src.storage == EvqIn))
2171         dst.storage = EvqInOut;
2172     else if ((dst.storage == EvqIn    && src.storage == EvqConst) ||
2173              (dst.storage == EvqConst && src.storage == EvqIn))
2174         dst.storage = EvqConstReadOnly;
2175     else if (src.storage != EvqTemporary)
2176         error(loc, "too many storage qualifiers", GetStorageQualifierString(src.storage), "");
2177
2178     // Precision qualifiers
2179     if (! force && src.precision != EpqNone && dst.precision != EpqNone)
2180         error(loc, "only one precision qualifier allowed", GetPrecisionQualifierString(src.precision), "");
2181     if (dst.precision == EpqNone || (force && src.precision != EpqNone))
2182         dst.precision = src.precision;
2183
2184     // Layout qualifiers
2185     mergeObjectLayoutQualifiers(loc, dst, src, false);
2186
2187     // individual qualifiers
2188     bool repeated = false;
2189     #define MERGE_SINGLETON(field) repeated |= dst.field && src.field; dst.field |= src.field;
2190     MERGE_SINGLETON(invariant);
2191     MERGE_SINGLETON(centroid);
2192     MERGE_SINGLETON(smooth);
2193     MERGE_SINGLETON(flat);
2194     MERGE_SINGLETON(nopersp);
2195     MERGE_SINGLETON(patch);
2196     MERGE_SINGLETON(sample);
2197     MERGE_SINGLETON(coherent);
2198     MERGE_SINGLETON(volatil);
2199     MERGE_SINGLETON(restrict);
2200     MERGE_SINGLETON(readonly);
2201     MERGE_SINGLETON(writeonly);
2202
2203     if (repeated)
2204         error(loc, "replicated qualifiers", "", "");
2205 }
2206
2207 void TParseContext::setDefaultPrecision(TSourceLoc loc, TPublicType& publicType, TPrecisionQualifier qualifier)
2208 {
2209     TBasicType basicType = publicType.basicType;
2210
2211     if (basicType == EbtSampler) {
2212         defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
2213
2214         return;  // all is well
2215     }
2216
2217     if (basicType == EbtInt || basicType == EbtFloat) {
2218         if (publicType.isScalar()) {
2219             defaultPrecision[basicType] = qualifier;
2220             if (basicType == EbtInt)
2221                 defaultPrecision[EbtUint] = qualifier;
2222
2223             return;  // all is well
2224         }
2225     }
2226
2227     if (basicType == EbtAtomicUint) {
2228         if (qualifier != EpqHigh)
2229             error(loc, "can only apply highp to atomic_uint", "precision", "");
2230
2231         return;
2232     }
2233
2234     error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
2235 }
2236
2237 // used to flatten the sampler type space into a single dimension
2238 // correlates with the declaration of defaultSamplerPrecision[]
2239 int TParseContext::computeSamplerTypeIndex(TSampler& sampler)
2240 {
2241     int arrayIndex   = sampler.arrayed   ? 1 : 0;
2242     int shadowIndex   = sampler.shadow   ? 1 : 0;
2243     int externalIndex = sampler.external ? 1 : 0;
2244
2245     return EsdNumDims * (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
2246 }
2247
2248 TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
2249 {
2250     if (publicType.basicType == EbtSampler)
2251         return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
2252     else
2253         return defaultPrecision[publicType.basicType];
2254 }
2255
2256 void TParseContext::precisionQualifierCheck(TSourceLoc loc, TPublicType& publicType)
2257 {
2258     // Built-in symbols are allowed some ambiguous precisions, to be pinned down
2259     // later by context.
2260     if (profile != EEsProfile || parsingBuiltins)
2261         return;
2262
2263     if (publicType.basicType == EbtAtomicUint && publicType.qualifier.precision != EpqNone && publicType.qualifier.precision != EpqHigh)
2264         error(loc, "atomic counters can only be highp", "atomic_uint", "");
2265
2266     if (publicType.basicType == EbtFloat || publicType.basicType == EbtUint || publicType.basicType == EbtInt || publicType.basicType == EbtSampler || publicType.basicType == EbtAtomicUint) {
2267         if (publicType.qualifier.precision == EpqNone) {
2268             if (messages & EShMsgRelaxedErrors)
2269                 warn(loc, "type requires declaration of default precision qualifier", TType::getBasicString(publicType.basicType), "substituting 'mediump'");
2270             else
2271                 error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(publicType.basicType), "");
2272             publicType.qualifier.precision = EpqMedium;
2273             defaultPrecision[publicType.basicType] = EpqMedium;
2274         }
2275     } else if (publicType.qualifier.precision != EpqNone)
2276         error(loc, "type cannot have precision qualifier", TType::getBasicString(publicType.basicType), "");
2277 }
2278
2279 void TParseContext::parameterTypeCheck(TSourceLoc loc, TStorageQualifier qualifier, const TType& type)
2280 {
2281     if ((qualifier == EvqOut || qualifier == EvqInOut) && (type.getBasicType() == EbtSampler || type.getBasicType() == EbtAtomicUint))
2282         error(loc, "samplers and atomic_uints cannot be output parameters", type.getBasicTypeString().c_str(), "");
2283 }
2284
2285 bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
2286 {
2287     if (type.getBasicType() == basicType)
2288         return true;
2289
2290     if (type.getBasicType() == EbtStruct) {
2291         const TTypeList& structure = *type.getStruct();
2292         for (unsigned int i = 0; i < structure.size(); ++i) {
2293             if (containsFieldWithBasicType(*structure[i].type, basicType))
2294                 return true;
2295         }
2296     }
2297
2298     return false;
2299 }
2300
2301 //
2302 // Do size checking for an array type's size.
2303 //
2304 void TParseContext::arraySizeCheck(TSourceLoc loc, TIntermTyped* expr, int& size)
2305 {
2306     TIntermConstantUnion* constant = expr->getAsConstantUnion();
2307     if (constant == 0 || (constant->getBasicType() != EbtInt && constant->getBasicType() != EbtUint)) {
2308         error(loc, "array size must be a constant integer expression", "", "");
2309         size = 1;
2310
2311         return;
2312     }
2313
2314     size = constant->getConstArray()[0].getIConst();
2315
2316     if (size <= 0) {
2317         error(loc, "array size must be a positive integer", "", "");
2318         size = 1;
2319
2320         return;
2321     }
2322 }
2323
2324 //
2325 // See if this qualifier can be an array.
2326 //
2327 // Returns true if there is an error.
2328 //
2329 bool TParseContext::arrayQualifierError(TSourceLoc loc, const TQualifier& qualifier)
2330 {
2331     if (qualifier.storage == EvqConst) {
2332         profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "const array");
2333         profileRequires(loc, EEsProfile, 300, 0, "const array");
2334     }
2335
2336     if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
2337         requireProfile(loc, ~EEsProfile, "vertex input arrays");
2338         profileRequires(loc, ENoProfile, 150, 0, "vertex input arrays");
2339     }
2340
2341     return false;
2342 }
2343
2344 //
2345 // Require array to have size
2346 //
2347 void TParseContext::arraySizeRequiredCheck(TSourceLoc loc, int size)
2348 {
2349     if (size == 0) {
2350         error(loc, "array size required", "", "");
2351         size = 1;
2352     }
2353 }
2354
2355 void TParseContext::structArrayCheck(TSourceLoc loc, TType* type)
2356 {
2357     const TTypeList& structure = *type->getStruct();
2358     for (int m = 0; m < (int)structure.size(); ++m) {
2359         const TType& member = *structure[m].type;
2360         if (member.isArray() && ! member.isExplicitlySizedArray())
2361             arraySizeRequiredCheck(structure[m].loc, 0);
2362     }
2363 }
2364
2365 void TParseContext::arrayDimError(TSourceLoc loc)
2366 {
2367     requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "arrays of arrays");
2368     profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, 0, "arrays of arrays");
2369     profileRequires(loc, EEsProfile, 310, 0, "arrays of arrays");
2370 }
2371
2372 void TParseContext::arrayDimCheck(TSourceLoc loc, TArraySizes* sizes1, TArraySizes* sizes2)
2373 {
2374     if ((sizes1 && sizes2) ||
2375         (sizes1 && sizes1->isArrayOfArrays()) ||
2376         (sizes2 && sizes2->isArrayOfArrays()))
2377         arrayDimError(loc);
2378 }
2379
2380 void TParseContext::arrayDimCheck(TSourceLoc loc, const TType* type, TArraySizes* sizes2)
2381 {
2382     if ((type && type->isArray() && sizes2) ||
2383         (sizes2 && sizes2->isArrayOfArrays()))
2384         arrayDimError(loc);
2385 }
2386
2387 //
2388 // Do all the semantic checking for declaring or redeclaring an array, with and
2389 // without a size, and make the right changes to the symbol table.
2390 //
2391 // size == 0 means no specified size.
2392 //
2393 void TParseContext::declareArray(TSourceLoc loc, TString& identifier, const TType& type, TSymbol*& symbol, bool& newDeclaration)
2394 {
2395     if (! symbol) {
2396         bool currentScope;
2397         symbol = symbolTable.find(identifier, 0, &currentScope);
2398
2399         if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
2400             // bad shader (errors already reported) trying to redeclare a built-in name as an array
2401             return;
2402         }
2403         if (symbol == 0 || ! currentScope) {
2404             //
2405             // Successfully process a new definition.
2406             // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
2407             //
2408             symbol = new TVariable(&identifier, type);
2409             symbolTable.insert(*symbol);
2410             newDeclaration = true;
2411
2412             if (! symbolTable.atBuiltInLevel()) {
2413                 if (isIoResizeArray(type)) {
2414                     ioArraySymbolResizeList.push_back(symbol);
2415                     checkIoArraysConsistency(loc, true);
2416                 } else
2417                     fixIoArraySize(loc, symbol->getWritableType());
2418             }
2419
2420             return;
2421         }
2422         if (symbol->getAsAnonMember()) {
2423             error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
2424             symbol = 0;
2425             return;
2426         }
2427     }
2428
2429     //
2430     // Process a redeclaration.
2431     //
2432
2433     if (! symbol) {
2434         error(loc, "array variable name expected", identifier.c_str(), "");
2435         return;
2436     }
2437
2438     // redeclareBuiltinVariable() should have already done the copyUp()
2439     TType& existingType = symbol->getWritableType();
2440
2441     if (! existingType.isArray()) {
2442         error(loc, "redeclaring non-array as array", identifier.c_str(), "");
2443         return;
2444     }
2445     if (existingType.isExplicitlySizedArray()) {
2446         // be more leniant for input arrays to geometry shaders and tessellation control outputs, where the redeclaration is the same size
2447         if (! (isIoResizeArray(type) && existingType.getArraySize() == type.getArraySize()))
2448             error(loc, "redeclaration of array with size", identifier.c_str(), "");
2449         return;
2450     }
2451
2452     if (! existingType.sameElementType(type)) {
2453         error(loc, "redeclaration of array with a different type", identifier.c_str(), "");
2454         return;
2455     }
2456
2457     arrayLimitCheck(loc, identifier, type.getArraySize());
2458
2459     existingType.updateArraySizes(type);
2460
2461     if (isIoResizeArray(type))
2462         checkIoArraysConsistency(loc);
2463 }
2464
2465 void TParseContext::updateImplicitArraySize(TSourceLoc loc, TIntermNode *node, int index)
2466 {
2467     // maybe there is nothing to do...
2468     TIntermTyped* typedNode = node->getAsTyped();
2469     if (typedNode->getType().getImplicitArraySize() > index)
2470         return;
2471
2472     // something to do...
2473
2474     // Figure out what symbol to lookup, as we will use its type to edit for the size change,
2475     // as that type will be shared through shallow copies for future references.
2476     TSymbol* symbol = 0;
2477     int blockIndex = -1;
2478     const TString* lookupName;
2479     if (node->getAsSymbolNode())
2480         lookupName = &node->getAsSymbolNode()->getName();
2481     else if (node->getAsBinaryNode()) {
2482         const TIntermBinary* deref = node->getAsBinaryNode();
2483         // This has to be the result of a block dereference, unless it's bad shader code
2484         if (! deref->getLeft()->getAsSymbolNode() || deref->getLeft()->getBasicType() != EbtBlock ||
2485             deref->getRight()->getAsConstantUnion() == 0)
2486             return;
2487
2488         blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
2489
2490         lookupName = &deref->getLeft()->getAsSymbolNode()->getName();
2491         if (IsAnonymous(*lookupName))
2492             lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName();
2493     }
2494
2495     // Lookup the symbol, should only fail if shader code is incorrect
2496     symbol = symbolTable.find(*lookupName);
2497     if (symbol == 0)
2498         return;
2499
2500     if (symbol->getAsFunction()) {
2501         error(loc, "array variable name expected", symbol->getName().c_str(), "");
2502         return;
2503     }
2504
2505     symbol->getWritableType().setImplicitArraySize(index + 1);
2506 }
2507
2508 //
2509 // Enforce non-initializer type/qualifier rules.
2510 //
2511 void TParseContext::nonInitConstCheck(TSourceLoc loc, TString& identifier, TType& type)
2512 {
2513     //
2514     // Make the qualifier make sense, given that there is an initializer.
2515     //
2516     if (type.getQualifier().storage == EvqConst ||
2517         type.getQualifier().storage == EvqConstReadOnly) {
2518         type.getQualifier().storage = EvqTemporary;
2519         error(loc, "variables with qualifier 'const' must be initialized", identifier.c_str(), "");
2520     }
2521 }
2522
2523 //
2524 // See if the identifier is a built-in symbol that can be redeclared, and if so,
2525 // copy the symbol table's read-only built-in variable to the current
2526 // global level, where it can be modified based on the passed in type.
2527 //
2528 // Returns 0 if no redeclaration took place; meaning a normal declaration still
2529 // needs to occur for it, not necessarily an error.
2530 //
2531 // Returns a redeclared and type-modified variable if a redeclarated occurred.
2532 //
2533 TSymbol* TParseContext::redeclareBuiltinVariable(TSourceLoc loc, const TString& identifier, const TQualifier& qualifier, const TShaderQualifiers& publicType, bool& newDeclaration)
2534 {
2535     if (profile == EEsProfile || ! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
2536         return 0;
2537
2538     // Special case when using GL_ARB_separate_shader_objects
2539     bool ssoPre150 = false;  // means the only reason this variable is redeclared is due to this combination
2540     if (version <= 140 && extensionsTurnedOn(1, &GL_ARB_separate_shader_objects)) {
2541         if (identifier == "gl_Position"     ||
2542             identifier == "gl_PointSize"    ||
2543             identifier == "gl_ClipVertex"   ||
2544             identifier == "gl_FogFragCoord")
2545             ssoPre150 = true;
2546     }
2547
2548     // Potentially redeclaring a built-in variable...
2549
2550     if (ssoPre150 ||
2551         (identifier == "gl_FragDepth"           && version >= 420) ||
2552         (identifier == "gl_FragCoord"           && version >= 150) ||
2553         (identifier == "gl_ClipDistance"        && version >= 130) ||
2554         (identifier == "gl_FrontColor"          && version >= 130) ||
2555         (identifier == "gl_BackColor"           && version >= 130) ||
2556         (identifier == "gl_FrontSecondaryColor" && version >= 130) ||
2557         (identifier == "gl_BackSecondaryColor"  && version >= 130) ||
2558         (identifier == "gl_SecondaryColor"      && version >= 130) ||
2559         (identifier == "gl_Color"               && version >= 130 && language == EShLangFragment) ||
2560          identifier == "gl_TexCoord") {
2561
2562         // Find the existing symbol, if any.
2563         bool builtIn;
2564         TSymbol* symbol = symbolTable.find(identifier, &builtIn);
2565
2566         // If the symbol was not found, this must be a version/profile/stage
2567         // that doesn't have it.
2568         if (! symbol)
2569             return 0;
2570
2571         // If it wasn't at a built-in level, then it's already been redeclared;
2572         // that is, this is a redeclaration of a redeclaration; reuse that initial
2573         // redeclaration.  Otherwise, make the new one.
2574         if (builtIn) {
2575             // Copy the symbol up to make a writable version
2576             makeEditable(symbol);
2577             newDeclaration = true;
2578         }
2579
2580         // Now, modify the type of the copy, as per the type of the current redeclaration.
2581
2582         TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
2583         if (ssoPre150) {            
2584             if (intermediate.inIoAccessed(identifier))
2585                 error(loc, "cannot redeclare after use", identifier.c_str(), "");
2586             if (qualifier.hasLayout())
2587                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
2588             if (qualifier.isMemory() || qualifier.isAuxiliary() || (language == EShLangVertex   && qualifier.storage != EvqVaryingOut) ||
2589                                                                    (language == EShLangFragment && qualifier.storage != EvqVaryingIn))
2590                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
2591             if (! qualifier.smooth)
2592                 error(loc, "cannot change interpolation qualification of", "redeclaration", symbol->getName().c_str());
2593         } else if (identifier == "gl_FrontColor"          ||
2594                    identifier == "gl_BackColor"           ||
2595                    identifier == "gl_FrontSecondaryColor" ||
2596                    identifier == "gl_BackSecondaryColor"  ||
2597                    identifier == "gl_SecondaryColor"      ||
2598                    identifier == "gl_Color") {
2599             symbolQualifier.flat = qualifier.flat;
2600             symbolQualifier.smooth = qualifier.smooth;
2601             symbolQualifier.nopersp = qualifier.nopersp;
2602             if (qualifier.hasLayout())
2603                 error(loc, "cannot apply layout qualifier to", "redeclaration", symbol->getName().c_str());
2604             if (qualifier.isMemory() || qualifier.isAuxiliary() || symbol->getType().getQualifier().storage != qualifier.storage)
2605                 error(loc, "cannot change storage, memory, or auxiliary qualification of", "redeclaration", symbol->getName().c_str());
2606         } else if (identifier == "gl_TexCoord" ||
2607                    identifier == "gl_ClipDistance") {
2608             if (qualifier.hasLayout() || qualifier.isMemory() || qualifier.isAuxiliary() ||
2609                 qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
2610                 symbolQualifier.storage != qualifier.storage)
2611                 error(loc, "cannot change qualification of", "redeclaration", symbol->getName().c_str());
2612         } else if (identifier == "gl_FragCoord") {
2613             if (intermediate.inIoAccessed("gl_FragCoord"))
2614                 error(loc, "cannot redeclare after use", "gl_FragCoord", "");
2615             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
2616                 qualifier.isMemory() || qualifier.isAuxiliary())
2617                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
2618             if (identifier == "gl_FragCoord" && qualifier.storage != EvqVaryingIn)
2619                 error(loc, "cannot change input storage qualification of", "redeclaration", symbol->getName().c_str());
2620             if (! builtIn && (publicType.pixelCenterInteger != intermediate.getPixelCenterInteger() || 
2621                               publicType.originUpperLeft != intermediate.getOriginUpperLeft()))
2622                 error(loc, "cannot redeclare with different qualification:", "redeclaration", symbol->getName().c_str());
2623             if (publicType.pixelCenterInteger)
2624                 intermediate.setPixelCenterInteger();
2625             if (publicType.originUpperLeft)
2626                 intermediate.setOriginUpperLeft();
2627         } else if (identifier == "gl_FragDepth") {
2628             if (qualifier.nopersp != symbolQualifier.nopersp || qualifier.flat != symbolQualifier.flat ||
2629                 qualifier.isMemory() || qualifier.isAuxiliary())
2630                 error(loc, "can only change layout qualification of", "redeclaration", symbol->getName().c_str());
2631             if (qualifier.storage != EvqVaryingOut)
2632                 error(loc, "cannot change output storage qualification of", "redeclaration", symbol->getName().c_str());
2633             if (publicType.layoutDepth != EldNone) {
2634                 if (intermediate.inIoAccessed("gl_FragDepth"))
2635                     error(loc, "cannot redeclare after use", "gl_FragDepth", "");
2636                 if (! intermediate.setDepth(publicType.layoutDepth))
2637                     error(loc, "all redeclarations must use the same depth layout on", "redeclaration", symbol->getName().c_str());
2638             }
2639
2640         }
2641         // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
2642
2643         return symbol;
2644     }
2645
2646     return 0;
2647 }
2648
2649 //
2650 // Either redeclare the requested block, or give an error message why it can't be done.
2651 //
2652 // TODO: functionality: explicitly sizing members of redeclared blocks is not giving them an explicit size
2653 void TParseContext::redeclareBuiltinBlock(TSourceLoc loc, TTypeList& newTypeList, const TString& blockName, const TString* instanceName, TArraySizes* arraySizes)
2654 {
2655     const char* feature = "built-in block redeclaration";
2656     requireProfile(loc, ~EEsProfile, feature);
2657     profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
2658
2659     if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment") {
2660         error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
2661         return;
2662     }
2663
2664     // Redeclaring a built-in block...
2665
2666     if (instanceName && ! builtInName(*instanceName)) {
2667         error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
2668         return;
2669     }
2670
2671     // Blocks with instance names are easy to find, lookup the instance name,
2672     // Anonymous blocks need to be found via a member.
2673     bool builtIn;
2674     TSymbol* block;
2675     if (instanceName)
2676         block = symbolTable.find(*instanceName, &builtIn);
2677     else
2678         block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
2679
2680     // If the block was not found, this must be a version/profile/stage
2681     // that doesn't have it, or the instance name is wrong.
2682     const char* errorName = instanceName ? instanceName->c_str() : newTypeList.front().type->getFieldName().c_str();
2683     if (! block) {
2684         error(loc, "no declaration found for redeclaration", errorName, "");
2685         return;
2686     }
2687     // Built-in blocks cannot be redeclared more than once, which if happened,
2688     // we'd be finding the already redeclared one here, rather than the built in.
2689     if (! builtIn) {
2690         error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
2691         return;
2692     }
2693
2694     // Copy the block to make a writable version, to insert into the block table after editing.
2695     block = symbolTable.copyUpDeferredInsert(block);
2696
2697     if (block->getType().getBasicType() != EbtBlock) {
2698         error(loc, "cannot redeclare a non block as a block", errorName, "");
2699         return;
2700     }
2701
2702     // Edit and error check the container against the redeclaration
2703     //  - remove unused members
2704     //  - ensure remaining qualifiers/types match
2705     TType& type = block->getWritableType();
2706     TTypeList::iterator member = type.getWritableStruct()->begin();
2707     size_t numOriginalMembersFound = 0;
2708     while (member != type.getStruct()->end()) {
2709         // look for match
2710         bool found = false;
2711         TTypeList::const_iterator newMember;
2712         TSourceLoc memberLoc;
2713         for (newMember = newTypeList.begin(); newMember != newTypeList.end(); ++newMember) {
2714             if (member->type->getFieldName() == newMember->type->getFieldName()) {
2715                 found = true;
2716                 memberLoc = newMember->loc;
2717                 break;
2718             }
2719         }
2720
2721         if (found) {
2722             ++numOriginalMembersFound;
2723             // - ensure match between redeclared members' types
2724             // - check for things that can't be changed
2725             // - update things that can be changed
2726             TType& oldType = *member->type;
2727             const TType& newType = *newMember->type;
2728             if (! newType.sameElementType(oldType))
2729                 error(memberLoc, "cannot redeclare block member with a different type", member->type->getFieldName().c_str(), "");
2730             if (oldType.isArray() != newType.isArray())
2731                 error(memberLoc, "cannot change arrayness of redeclared block member", member->type->getFieldName().c_str(), "");
2732             else if (! oldType.sameArrayness(newType) && oldType.isExplicitlySizedArray())
2733                 error(memberLoc, "cannot change array size of redeclared block member", member->type->getFieldName().c_str(), "");
2734             else if (newType.isArray())
2735                 arrayLimitCheck(loc, member->type->getFieldName(), newType.getArraySize());
2736             if (newType.getQualifier().isMemory())
2737                 error(memberLoc, "cannot add memory qualifier to redeclared block member", member->type->getFieldName().c_str(), "");
2738             if (newType.getQualifier().hasLayout())
2739                 error(memberLoc, "cannot add layout to redeclared block member", member->type->getFieldName().c_str(), "");
2740             if (newType.getQualifier().patch)
2741                 error(memberLoc, "cannot add patch to redeclared block member", member->type->getFieldName().c_str(), "");
2742             oldType.getQualifier().centroid = newType.getQualifier().centroid;
2743             oldType.getQualifier().sample = newType.getQualifier().sample;
2744             oldType.getQualifier().invariant = newType.getQualifier().invariant;
2745             oldType.getQualifier().smooth = newType.getQualifier().smooth;
2746             oldType.getQualifier().flat = newType.getQualifier().flat;
2747             oldType.getQualifier().nopersp = newType.getQualifier().nopersp;
2748
2749             // go to next member
2750             ++member;
2751         } else {    
2752             // For missing members of anonymous blocks that have been redeclared,
2753             // hide the original (shared) declaration.
2754             // Instance-named blocks can just have the member removed.
2755             if (instanceName)
2756                 member = type.getWritableStruct()->erase(member);
2757             else {
2758                 member->type->hideMember();
2759                 ++member;
2760             }
2761         }
2762     }
2763
2764     if (numOriginalMembersFound < newTypeList.size())
2765         error(loc, "block redeclaration has extra members", blockName.c_str(), "");
2766     if (type.isArray() != (arraySizes != 0))
2767         error(loc, "cannot change arrayness of redeclared block", blockName.c_str(), "");
2768     else if (type.isArray()) {
2769         if (type.isExplicitlySizedArray() && arraySizes->getSize() == 0)
2770             error(loc, "block already declared with size, can't redeclare as implicitly-sized", blockName.c_str(), "");
2771         else if (type.isExplicitlySizedArray() && type.getArraySize() != arraySizes->getSize())
2772             error(loc, "cannot change array size of redeclared block", blockName.c_str(), "");
2773         else if (type.isImplicitlySizedArray() && arraySizes->getSize() > 0)
2774             type.changeArraySize(arraySizes->getSize());
2775     }
2776
2777     symbolTable.insert(*block);
2778
2779     // Check for general layout qualifier errors
2780     layoutObjectCheck(loc, *block);
2781
2782     // Tracking for implicit sizing of array
2783     if (isIoResizeArray(block->getType())) {
2784         ioArraySymbolResizeList.push_back(block);
2785         checkIoArraysConsistency(loc, true);
2786     } else if (block->getType().isArray())
2787         fixIoArraySize(loc, block->getWritableType());
2788
2789     // Save it in the AST for linker use.
2790     intermediate.addSymbolLinkageNode(linkage, *block);
2791 }
2792
2793 void TParseContext::paramCheckFix(TSourceLoc loc, const TStorageQualifier& qualifier, TType& type)
2794 {
2795     switch (qualifier) {
2796     case EvqConst:
2797     case EvqConstReadOnly:
2798         type.getQualifier().storage = EvqConstReadOnly;
2799         break;
2800     case EvqIn:
2801     case EvqOut:
2802     case EvqInOut:
2803         type.getQualifier().storage = qualifier;
2804         break;
2805     case EvqTemporary:
2806         type.getQualifier().storage = EvqIn;
2807         break;
2808     default:
2809         type.getQualifier().storage = EvqIn;
2810         error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
2811         break;
2812     }
2813 }
2814
2815 void TParseContext::paramCheckFix(TSourceLoc loc, const TQualifier& qualifier, TType& type)
2816 {
2817     if (qualifier.isMemory()) {
2818         type.getQualifier().volatil   = qualifier.volatil;
2819         type.getQualifier().coherent  = qualifier.coherent;
2820         type.getQualifier().readonly  = qualifier.readonly;
2821         type.getQualifier().writeonly = qualifier.writeonly;
2822         type.getQualifier().restrict  = qualifier.restrict;
2823     }
2824     if (qualifier.isAuxiliary() ||
2825         qualifier.isInterpolation())
2826         error(loc, "cannot use auxiliary or interpolation qualifiers on a function parameter", "", "");
2827     if (qualifier.hasLayout())
2828         error(loc, "cannot use layout qualifiers on a function parameter", "", "");
2829     if (qualifier.invariant)
2830         error(loc, "cannot use invariant qualifier on a function parameter", "", "");    
2831
2832     paramCheckFix(loc, qualifier.storage, type);
2833 }
2834
2835 void TParseContext::nestedBlockCheck(TSourceLoc loc)
2836 {
2837     if (structNestingLevel > 0)
2838         error(loc, "cannot nest a block definition inside a structure or block", "", "");
2839     ++structNestingLevel;
2840 }
2841
2842 void TParseContext::nestedStructCheck(TSourceLoc loc)
2843 {
2844     if (structNestingLevel > 0)
2845         error(loc, "cannot nest a structure definition inside a structure or block", "", "");
2846     ++structNestingLevel;
2847 }
2848
2849 void TParseContext::arrayObjectCheck(TSourceLoc loc, const TType& type, const char* op)
2850 {
2851     // Some versions don't allow comparing arrays or structures containing arrays
2852     if (type.containsArray()) {
2853         profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, op);
2854         profileRequires(loc, EEsProfile, 300, 0, op);
2855     }
2856 }
2857
2858 void TParseContext::opaqueCheck(TSourceLoc loc, const TType& type, const char* op)
2859 {
2860     if (containsFieldWithBasicType(type, EbtSampler))
2861         error(loc, "can't use with samplers or structs containing samplers", op, "");
2862 }
2863
2864 void TParseContext::structTypeCheck(TSourceLoc loc, TPublicType& publicType)
2865 {
2866     const TTypeList& typeList = *publicType.userDef->getStruct();
2867
2868     // fix and check for member storage qualifiers and types that don't belong within a structure
2869     for (unsigned int member = 0; member < typeList.size(); ++member) {
2870         TQualifier& memberQualifier = typeList[member].type->getQualifier();        
2871         TSourceLoc memberLoc = typeList[member].loc;
2872         if (memberQualifier.isAuxiliary() ||
2873             memberQualifier.isInterpolation() ||
2874             (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal))
2875             error(memberLoc, "cannot use storage or interpolation qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
2876         if (memberQualifier.isMemory())
2877             error(memberLoc, "cannot use memory qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
2878         if (memberQualifier.hasLayout()) {
2879             error(memberLoc, "cannot use layout qualifiers on structure members", typeList[member].type->getFieldName().c_str(), "");
2880             memberQualifier.clearLayout();
2881         }
2882         if (memberQualifier.invariant)
2883             error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
2884     }
2885 }
2886
2887 //
2888 // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
2889 //
2890 // "The loop index has type int or float.
2891 //
2892 // "The for statement has the form:
2893 //     for ( init-declaration ; condition ; expression )
2894 //     init-declaration has the form: type-specifier identifier = constant-expression
2895 //     condition has the form:  loop-index relational_operator constant-expression
2896 //         where relational_operator is one of: > >= < <= == or !=
2897 //     expression [sic] has one of the following forms:
2898 //         loop-index++
2899 //         loop-index--
2900 //         loop-index += constant-expression
2901 //         loop-index -= constant-expression
2902 //
2903 // The body is handled in an AST traversal.
2904 //
2905 void TParseContext::inductiveLoopCheck(TSourceLoc loc, TIntermNode* init, TIntermLoop* loop)
2906 {
2907     // loop index init must exist and be a declaration, which shows up in the AST as an aggregate of size 1 of the declaration
2908     bool badInit = false;
2909     if (! init || ! init->getAsAggregate() || ! init->getAsAggregate()->getSequence().size() == 1)
2910         badInit = true;
2911     TIntermBinary* binaryInit;
2912     if (! badInit) {
2913         // get the declaration assignment
2914         binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
2915         if (! binaryInit)
2916             badInit = true;
2917     }
2918     if (badInit) {
2919         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
2920         return;
2921     }
2922
2923     // loop index must be type int or float
2924     if (! binaryInit->getType().isScalar() || (binaryInit->getBasicType() != EbtInt && binaryInit->getBasicType() != EbtFloat)) {
2925         error(loc, "inductive loop requires a scalar 'int' or 'float' loop index", "limitations", "");
2926         return;
2927     }
2928
2929     // init is the form "loop-index = constant"
2930     if (binaryInit->getOp() != EOpAssign || ! binaryInit->getLeft()->getAsSymbolNode() || ! binaryInit->getRight()->getAsConstantUnion()) {
2931         error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
2932         return;
2933     }
2934
2935     // get the unique id of the loop index
2936     int loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
2937     inductiveLoopIds.insert(loopIndex);
2938
2939     // condition's form must be "loop-index relational-operator constant-expression"
2940     bool badCond = ! loop->getTest();
2941     if (! badCond) {
2942         TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
2943         badCond = ! binaryCond;
2944         if (! badCond) {
2945             switch (binaryCond->getOp()) {
2946             case EOpGreaterThan:
2947             case EOpGreaterThanEqual:
2948             case EOpLessThan:
2949             case EOpLessThanEqual:
2950             case EOpEqual:
2951             case EOpNotEqual:
2952                 break;
2953             default:
2954                 badCond = true;
2955             }
2956         }
2957         if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
2958                            binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
2959                            ! binaryCond->getRight()->getAsConstantUnion()))
2960             badCond = true;
2961     }
2962     if (badCond) {
2963         error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
2964         return;
2965     }
2966
2967     // loop-index++
2968     // loop-index--
2969     // loop-index += constant-expression
2970     // loop-index -= constant-expression
2971     bool badTerminal = ! loop->getTerminal();
2972     if (! badTerminal) {
2973         TIntermUnary* unaryTerminal = loop->getTerminal()->getAsUnaryNode();
2974         TIntermBinary* binaryTerminal = loop->getTerminal()->getAsBinaryNode();
2975         if (unaryTerminal || binaryTerminal) {
2976             switch(loop->getTerminal()->getAsOperator()->getOp()) {
2977             case EOpPostDecrement:
2978             case EOpPostIncrement:
2979             case EOpAddAssign:
2980             case EOpSubAssign:
2981                 break;
2982             default:
2983                 badTerminal = true;
2984             }
2985         } else
2986             badTerminal = true;
2987         if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
2988                                binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
2989                                ! binaryTerminal->getRight()->getAsConstantUnion()))
2990             badTerminal = true;
2991         if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
2992                               unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
2993             badTerminal = true;
2994     }
2995     if (badTerminal) {
2996         error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
2997         return;
2998     }
2999
3000     // the body
3001     inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
3002 }
3003
3004 // Do limit checks against for all built-in arrays.
3005 void TParseContext::arrayLimitCheck(TSourceLoc loc, const TString& identifier, int size)
3006 {
3007     if (identifier.compare("gl_TexCoord") == 0)
3008         limitCheck(loc, size, "gl_MaxTextureCoords", "gl_TexCoord array size");
3009     else if (identifier.compare("gl_ClipDistance") == 0)
3010         limitCheck(loc, size, "gl_MaxClipDistances", "gl_ClipDistance array size");
3011 }
3012
3013 // See if the provide value is less than the symbol indicated by limit,
3014 // which should be a constant in the symbol table.
3015 void TParseContext::limitCheck(TSourceLoc loc, int value, const char* limit, const char* feature)
3016 {
3017     TSymbol* symbol = symbolTable.find(limit);
3018     assert(symbol->getAsVariable());
3019     const TConstUnionArray& constArray = symbol->getAsVariable()->getConstArray();
3020     assert(! constArray.empty());
3021     if (value >= constArray[0].getIConst())
3022         error(loc, "must be less than", feature, "%s (%d)", limit, constArray[0].getIConst());
3023 }
3024
3025 //
3026 // Do any additional error checking, etc., once we know the parsing is done.
3027 //
3028 void TParseContext::finalErrorCheck()
3029 {
3030     // Check on array indexes for ES 2.0 (version 100) limitations.
3031     for (size_t i = 0; i < needsIndexLimitationChecking.size(); ++i)
3032         constantIndexExpressionCheck(needsIndexLimitationChecking[i]);
3033 }
3034
3035 //
3036 // Layout qualifier stuff.
3037 //
3038
3039 // Put the id's layout qualification into the public type, for qualifiers not having a number set.
3040 // This is before we know any type information for error checking.
3041 void TParseContext::setLayoutQualifier(TSourceLoc loc, TPublicType& publicType, TString& id)
3042 {
3043     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
3044
3045     if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
3046         publicType.qualifier.layoutMatrix = ElmColumnMajor;
3047         return;
3048     }
3049     if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
3050         publicType.qualifier.layoutMatrix = ElmRowMajor;
3051         return;
3052     }
3053     if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
3054         publicType.qualifier.layoutPacking = ElpPacked;
3055         return;
3056     }
3057     if (id == TQualifier::getLayoutPackingString(ElpShared)) {
3058         publicType.qualifier.layoutPacking = ElpShared;
3059         return;
3060     }
3061     if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
3062         publicType.qualifier.layoutPacking = ElpStd140;
3063         return;
3064     }
3065     if (id == TQualifier::getLayoutPackingString(ElpStd430)) {
3066         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "std430");
3067         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, 0, "std430");
3068         profileRequires(loc, EEsProfile, 310, 0, "std430");
3069         publicType.qualifier.layoutPacking = ElpStd430;
3070         return;
3071     }
3072     for (TLayoutFormat format = (TLayoutFormat)(ElfNone + 1); format < ElfCount; format = (TLayoutFormat)(format + 1)) {
3073         if (id == TQualifier::getLayoutFormatString(format)) {
3074             if ((format > ElfEsFloatGuard && format < ElfFloatGuard) ||
3075                 (format > ElfEsIntGuard && format < ElfIntGuard) ||
3076                 (format > ElfEsUintGuard && format < ElfCount))
3077                 requireProfile(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, "image load-store format");
3078             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, GL_ARB_shader_image_load_store, "image load store");
3079             profileRequires(loc, EEsProfile, 310, GL_ARB_shader_image_load_store, "image load store");
3080             publicType.qualifier.layoutFormat = format;
3081             return;
3082         }
3083     }
3084     if (language == EShLangGeometry || language == EShLangTessEvaluation) {
3085         if (id == TQualifier::getGeometryString(ElgTriangles)) {
3086             publicType.shaderQualifiers.geometry = ElgTriangles;
3087             return;
3088         }
3089         if (language == EShLangGeometry) {
3090             if (id == TQualifier::getGeometryString(ElgPoints)) {
3091                 publicType.shaderQualifiers.geometry = ElgPoints;
3092                 return;
3093             }
3094             if (id == TQualifier::getGeometryString(ElgLineStrip)) {
3095                 publicType.shaderQualifiers.geometry = ElgLineStrip;
3096                 return;
3097             }
3098             if (id == TQualifier::getGeometryString(ElgLines)) {
3099                 publicType.shaderQualifiers.geometry = ElgLines;
3100                 return;
3101             }
3102             if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
3103                 publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
3104                 return;
3105             }
3106             if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
3107                 publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
3108                 return;
3109             }
3110             if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
3111                 publicType.shaderQualifiers.geometry = ElgTriangleStrip;
3112                 return;
3113             }
3114         } else {
3115             assert(language == EShLangTessEvaluation);
3116
3117             // input primitive
3118             if (id == TQualifier::getGeometryString(ElgTriangles)) {
3119                 publicType.shaderQualifiers.geometry = ElgTriangles;
3120                 return;
3121             }
3122             if (id == TQualifier::getGeometryString(ElgQuads)) {
3123                 publicType.shaderQualifiers.geometry = ElgQuads;
3124                 return;
3125             }
3126             if (id == TQualifier::getGeometryString(ElgIsolines)) {
3127                 publicType.shaderQualifiers.geometry = ElgIsolines;
3128                 return;
3129             }
3130
3131             // vertex spacing
3132             if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
3133                 publicType.shaderQualifiers.spacing = EvsEqual;
3134                 return;
3135             }
3136             if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
3137                 publicType.shaderQualifiers.spacing = EvsFractionalEven;
3138                 return;
3139             }
3140             if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
3141                 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
3142                 return;
3143             }
3144
3145             // triangle order
3146             if (id == TQualifier::getVertexOrderString(EvoCw)) {
3147                 publicType.shaderQualifiers.order = EvoCw;
3148                 return;
3149             }
3150             if (id == TQualifier::getVertexOrderString(EvoCcw)) {
3151                 publicType.shaderQualifiers.order = EvoCcw;
3152                 return;
3153             }
3154
3155             // point mode
3156             if (id == "point_mode") {
3157                 publicType.shaderQualifiers.pointMode = true;
3158                 return;
3159             }
3160         }
3161     }
3162     if (language == EShLangFragment) {
3163         if (id == "origin_upper_left") {
3164             requireProfile(loc, ECoreProfile | ECompatibilityProfile, "origin_upper_left");
3165             publicType.shaderQualifiers.originUpperLeft = true;
3166             return;
3167         }
3168         if (id == "pixel_center_integer") {
3169             requireProfile(loc, ECoreProfile | ECompatibilityProfile, "pixel_center_integer");
3170             publicType.shaderQualifiers.pixelCenterInteger = true;
3171             return;
3172         }
3173         if (id == "early_fragment_tests") {
3174             profileRequires(loc, ENoProfile | ECoreProfile | ECompatibilityProfile, 420, GL_ARB_shader_image_load_store, "early_fragment_tests");
3175             profileRequires(loc, EEsProfile, 310, 0, "early_fragment_tests");
3176             publicType.shaderQualifiers.earlyFragmentTests = true;
3177             return;
3178         }
3179         for (TLayoutDepth depth = (TLayoutDepth)(EldNone + 1); depth < EldCount; depth = (TLayoutDepth)(depth+1)) {
3180             if (id == TQualifier::getLayoutDepthString(depth)) {
3181                 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "depth layout qualifier");
3182                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 0, "depth layout qualifier");
3183                 publicType.shaderQualifiers.layoutDepth = depth;
3184                 return;
3185             }
3186         }
3187     }
3188     error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
3189 }
3190
3191 // Put the id's layout qualifier value into the public type, for qualifiers having a number set.
3192 // This is before we know any type information for error checking.
3193 void TParseContext::setLayoutQualifier(TSourceLoc loc, TPublicType& publicType, TString& id, const TIntermTyped* node)
3194 {
3195     const char* feature = "layout-id value";
3196     const char* nonLiteralFeature = "non-literal layout-id value";
3197
3198     integerCheck(node, feature);
3199     const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
3200     int value;
3201     if (constUnion) {
3202         value = constUnion->getConstArray()[0].getIConst();
3203         if (! constUnion->isLiteral()) {
3204             requireProfile(loc, ECoreProfile | ECompatibilityProfile, nonLiteralFeature);
3205             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, nonLiteralFeature);
3206         }
3207     } else {
3208         // grammar should have give out the error message
3209         value = 0;
3210     }
3211
3212     if (value < 0) {
3213         error(loc, "cannot be negative", feature, "");
3214         return;
3215     }
3216
3217     std::transform(id.begin(), id.end(), id.begin(), ::tolower);
3218     
3219     if (id == "offset") {
3220         const char* feature = "uniform offset";
3221         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
3222         const char* exts[2] = { GL_ARB_enhanced_layouts, GL_ARB_shader_atomic_counters };
3223         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 420, 2, exts, feature);
3224         profileRequires(loc, EEsProfile, 310, 0, feature);
3225         publicType.qualifier.layoutOffset = value;
3226         return;
3227     } else if (id == "align") {
3228         const char* feature = "uniform buffer-member align";
3229         requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
3230         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, feature);
3231         // "The specified alignment must be a power of 2, or a compile-time error results."
3232         if (! IsPow2(value))
3233             error(loc, "must be a power of 2", "align", "");
3234         else
3235             publicType.qualifier.layoutAlign = value;
3236         return;
3237     } else if (id == "location") {
3238         profileRequires(loc, EEsProfile, 300, 0, "location");
3239         const char* exts[2] = { GL_ARB_separate_shader_objects, GL_ARB_explicit_attrib_location };
3240         profileRequires(loc, ~EEsProfile, 330, 2, exts, "location");
3241         if ((unsigned int)value >= TQualifier::layoutLocationEnd)
3242             error(loc, "location is too large", id.c_str(), "");
3243         else
3244             publicType.qualifier.layoutLocation = value;
3245         return;
3246     } else if (id == "binding") {
3247         profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, "binding");
3248         profileRequires(loc, EEsProfile, 310, 0, "binding");
3249         if ((unsigned int)value >= TQualifier::layoutBindingEnd)
3250             error(loc, "binding is too large", id.c_str(), "");
3251         else
3252             publicType.qualifier.layoutBinding = value;
3253         return;
3254     } else if (id == "component") {
3255         requireProfile(loc, ECoreProfile | ECompatibilityProfile, "component");
3256         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, "component");
3257         if ((unsigned)value >= TQualifier::layoutComponentEnd)
3258             error(loc, "component is too large", id.c_str(), "");
3259         else
3260             publicType.qualifier.layoutComponent = value;
3261         return;
3262     } else if (id.compare(0, 4, "xfb_") == 0) {
3263         // "Any shader making any static use (after preprocessing) of any of these 
3264         // *xfb_* qualifiers will cause the shader to be in a transform feedback 
3265         // capturing mode and hence responsible for describing the transform feedback 
3266         // setup."
3267         intermediate.setXfbMode();
3268         const char* feature = "transform feedback qualifier";
3269         requireStage(loc, (EShLanguageMask)(EShLangVertexMask | EShLangGeometryMask | EShLangTessControlMask | EShLangTessEvaluationMask), feature);
3270         requireProfile(loc, ECoreProfile | ECompatibilityProfile, feature);
3271         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, feature);
3272         if (id == "xfb_buffer") {
3273             // "It is a compile-time error to specify an *xfb_buffer* that is greater than
3274             // the implementation-dependent constant gl_MaxTransformFeedbackBuffers."
3275             if (value >= resources.maxTransformFeedbackBuffers)
3276                 error(loc, "buffer is too large:", id.c_str(), "gl_MaxTransformFeedbackBuffers is %d", resources.maxTransformFeedbackBuffers);                
3277             if (value >= TQualifier::layoutXfbBufferEnd)
3278                 error(loc, "buffer is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbBufferEnd-1);
3279             else
3280                 publicType.qualifier.layoutXfbBuffer = value;
3281             return;
3282         } else if (id == "xfb_offset") {
3283             if (value >= TQualifier::layoutXfbOffsetEnd)
3284                 error(loc, "offset is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbOffsetEnd-1);
3285             else
3286                 publicType.qualifier.layoutXfbOffset = value;
3287             return;
3288         } else if (id == "xfb_stride") {
3289             // "The resulting stride (implicit or explicit), when divided by 4, must be less than or equal to the 
3290             // implementation-dependent constant gl_MaxTransformFeedbackInterleavedComponents."
3291             if (value > 4 * resources.maxTransformFeedbackInterleavedComponents)
3292                 error(loc, "1/4 stride is too large:", id.c_str(), "gl_MaxTransformFeedbackInterleavedComponents is %d", resources.maxTransformFeedbackInterleavedComponents);
3293             else if (value >= TQualifier::layoutXfbStrideEnd)
3294                 error(loc, "stride is too large:", id.c_str(), "internal max is %d", TQualifier::layoutXfbStrideEnd-1);
3295             if (value < TQualifier::layoutXfbStrideEnd)
3296                 publicType.qualifier.layoutXfbStride = value;
3297             return;
3298         }
3299     }
3300
3301     switch (language) {
3302     case EShLangVertex:
3303         break;
3304
3305     case EShLangTessControl:
3306         if (id == "vertices") {
3307             publicType.shaderQualifiers.vertices = value;
3308             return;
3309         }
3310         break;
3311
3312     case EShLangTessEvaluation:
3313         break;
3314
3315     case EShLangGeometry:
3316         if (id == "invocations") {
3317             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, 0, "invocations");
3318             publicType.shaderQualifiers.invocations = value;
3319             return;
3320         }
3321         if (id == "max_vertices") {
3322             publicType.shaderQualifiers.vertices = value;
3323             if (value > resources.maxGeometryOutputVertices)
3324                 error(loc, "too large, must be less than gl_MaxGeometryOutputVertices", "max_vertices", "");
3325             return;
3326         }
3327         if (id == "stream") {
3328             publicType.qualifier.layoutStream = value;
3329             return;
3330         }
3331         break;
3332
3333     case EShLangFragment:
3334         if (id == "index") {
3335             requireProfile(loc, ECompatibilityProfile | ECoreProfile, "index layout qualifier on fragment output");
3336             const char* exts[2] = { GL_ARB_separate_shader_objects, GL_ARB_explicit_attrib_location };
3337             profileRequires(loc, ECompatibilityProfile | ECoreProfile, 330, 2, exts, "index layout qualifier on fragment output");
3338             publicType.qualifier.layoutIndex = value;
3339             return;
3340         }
3341         break;
3342
3343     case EShLangCompute:
3344         if (id == "local_size_x") {
3345             publicType.shaderQualifiers.localSize[0] = value;
3346             return;
3347         }
3348         if (id == "local_size_y") {
3349             publicType.shaderQualifiers.localSize[1] = value;
3350             return;
3351         }
3352         if (id == "local_size_z") {
3353             publicType.shaderQualifiers.localSize[2] = value;
3354             return;
3355         }
3356         break;
3357
3358     default:
3359         break;
3360     }
3361
3362     error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
3363 }
3364
3365 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
3366 //
3367 // "More than one layout qualifier may appear in a single declaration.
3368 // Additionally, the same layout-qualifier-name can occur multiple times 
3369 // within a layout qualifier or across multiple layout qualifiers in the 
3370 // same declaration. When the same layout-qualifier-name occurs 
3371 // multiple times, in a single declaration, the last occurrence overrides 
3372 // the former occurrence(s).  Further, if such a layout-qualifier-name 
3373 // will effect subsequent declarations or other observable behavior, it 
3374 // is only the last occurrence that will have any effect, behaving as if 
3375 // the earlier occurrence(s) within the declaration are not present.  
3376 // This is also true for overriding layout-qualifier-names, where one 
3377 // overrides the other (e.g., row_major vs. column_major); only the last 
3378 // occurrence has any effect."    
3379 //
3380 void TParseContext::mergeObjectLayoutQualifiers(TSourceLoc loc, TQualifier& dst, const TQualifier& src, bool inheritOnly)
3381 {
3382     if (src.hasMatrix())
3383         dst.layoutMatrix = src.layoutMatrix;
3384     if (src.hasPacking())
3385         dst.layoutPacking = src.layoutPacking;
3386
3387     if (src.hasStream())
3388         dst.layoutStream = src.layoutStream;
3389
3390     if (src.hasFormat())
3391         dst.layoutFormat = src.layoutFormat;
3392
3393     if (src.hasXfbBuffer())
3394         dst.layoutXfbBuffer = src.layoutXfbBuffer;
3395
3396     if (src.hasAlign())
3397         dst.layoutAlign = src.layoutAlign;
3398
3399     if (! inheritOnly) {
3400         if (src.hasLocation())
3401             dst.layoutLocation = src.layoutLocation;
3402         if (src.hasComponent())
3403             dst.layoutComponent = src.layoutComponent;
3404         if (src.hasIndex())
3405             dst.layoutIndex = src.layoutIndex;
3406
3407         if (src.hasOffset())
3408             dst.layoutOffset = src.layoutOffset;
3409
3410         if (src.layoutBinding != TQualifier::layoutBindingEnd)
3411             dst.layoutBinding = src.layoutBinding;
3412
3413         if (src.hasXfbStride())
3414             dst.layoutXfbStride = src.layoutXfbStride;
3415         if (src.hasXfbOffset())
3416             dst.layoutXfbOffset = src.layoutXfbOffset;
3417     }
3418 }
3419
3420 // Do error layout error checking given a full variable/block declaration.
3421 void TParseContext::layoutObjectCheck(TSourceLoc loc, const TSymbol& symbol)
3422 {
3423     const TType& type = symbol.getType();
3424     const TQualifier& qualifier = type.getQualifier();
3425
3426     // first, cross check WRT to just the type
3427     layoutTypeCheck(loc, type);
3428
3429     // now, any remaining error checking based on the object itself
3430
3431     if (qualifier.hasAnyLocation()) {
3432         switch (qualifier.storage) {
3433         case EvqUniform:
3434         case EvqBuffer:
3435             if (symbol.getAsVariable() == 0)
3436                 error(loc, "can only be used on variable declaration", "location", "");
3437             break;
3438         default:
3439             break;
3440         }
3441     }
3442
3443     // Check packing and matrix 
3444     if (qualifier.hasUniformLayout()) {
3445         switch (qualifier.storage) {
3446         case EvqUniform:
3447         case EvqBuffer:
3448             if (type.getBasicType() != EbtBlock) {
3449                 if (qualifier.hasMatrix())
3450                     error(loc, "cannot specify matrix layout on a variable declaration", "layout", "");
3451                 if (qualifier.hasPacking())
3452                     error(loc, "cannot specify packing on a variable declaration", "layout", "");
3453                 // "The offset qualifier can only be used on block members of blocks..."
3454                 if (qualifier.hasOffset() && type.getBasicType() != EbtAtomicUint)
3455                     error(loc, "cannot specify on a variable declaration", "offset", "");
3456                 // "The align qualifier can only be used on blocks or block members..."
3457                 if (qualifier.hasAlign())
3458                     error(loc, "cannot specify on a variable declaration", "align", "");
3459             }
3460             break;
3461         default:
3462             // these were already filtered by layoutTypeCheck() (or its callees)
3463             break;
3464         }
3465     }
3466 }
3467
3468 // Do layout error checking with respect to a type.
3469 void TParseContext::layoutTypeCheck(TSourceLoc loc, const TType& type)
3470 {
3471     const TQualifier& qualifier = type.getQualifier();
3472
3473     // first, intra layout qualifier-only error checking
3474     layoutQualifierCheck(loc, qualifier);
3475
3476     // now, error checking combining type and qualifier
3477
3478     if (qualifier.hasAnyLocation()) {
3479         if (qualifier.hasLocation()) {
3480             if (qualifier.storage == EvqVaryingOut && language == EShLangFragment) {
3481                 if (qualifier.layoutLocation >= (unsigned int)resources.maxDrawBuffers)
3482                     error(loc, "too large for fragment output", "location", "");
3483             }
3484         }
3485         if (qualifier.hasComponent()) {
3486             // "It is a compile-time error if this sequence of components gets larger than 3."
3487             if (qualifier.layoutComponent + type.getVectorSize() > 4)
3488                 error(loc, "type overflows the available 4 components", "component", "");
3489
3490             // "It is a compile-time error to apply the component qualifier to a matrix, a structure, a block, or an array containing any of these."
3491             if (type.isMatrix() || type.getBasicType() == EbtBlock || type.getBasicType() == EbtStruct)
3492                 error(loc, "cannot apply to a matrix, structure, or block", "component", "");
3493         }
3494
3495         switch (qualifier.storage) {
3496         case EvqVaryingIn:
3497         case EvqVaryingOut:
3498             if (type.getBasicType() == EbtBlock)
3499                 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, "location qualifier on in/out block");
3500             break;
3501         case EvqUniform:
3502         case EvqBuffer:
3503             break;
3504         default:
3505             error(loc, "can only appy to uniform, buffer, in, or out storage qualifiers", "location", "");
3506             break;
3507         }
3508
3509         bool typeCollision;
3510         int repeated = intermediate.addUsedLocation(qualifier, type, typeCollision);
3511         if (repeated >= 0 && ! typeCollision)
3512             error(loc, "overlapping use of location", "location", "%d", repeated);
3513         // "fragment-shader outputs ... if two variables are placed within the same
3514         // location, they must have the same underlying type (floating-point or integer)"
3515         if (typeCollision && language == EShLangFragment && qualifier.isPipeOutput())
3516             error(loc, "fragment outputs sharing the same location must be the same basic type", "location", "%d", repeated);
3517     }
3518
3519     if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
3520         int repeated = intermediate.addXfbBufferOffset(type);
3521         if (repeated >= 0)
3522             error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
3523
3524         // "The offset must be a multiple of the size of the first component of the first 
3525         // qualified variable or block member, or a compile-time error results. Further, if applied to an aggregate 
3526         // containing a double, the offset must also be a multiple of 8..."
3527         if (type.containsBasicType(EbtDouble) && ! IsMultipleOfPow2(qualifier.layoutXfbOffset, 8))
3528             error(loc, "type contains double; xfb_offset must be a multiple of 8", "xfb_offset", "");
3529         else if (! IsMultipleOfPow2(qualifier.layoutXfbOffset, 4))
3530             error(loc, "must be a multiple of size of first component", "xfb_offset", "");
3531     }
3532
3533     if (qualifier.hasXfbStride() && qualifier.hasXfbBuffer()) {
3534         if (! intermediate.setXfbBufferStride(qualifier.layoutXfbBuffer, qualifier.layoutXfbStride))
3535             error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
3536     }
3537
3538     if (qualifier.hasBinding()) {
3539         // Binding checking, from the spec:
3540         //
3541         // "If the binding point for any uniform or shader storage block instance is less than zero, or greater than or
3542         // equal to the implementation-dependent maximum number of uniform buffer bindings, a compile-time
3543         // error will occur. When the binding identifier is used with a uniform or shader storage block instanced as
3544         // an array of size N, all elements of the array from binding through binding + N \96 1 must be within this
3545         // range."
3546         //
3547         if (type.getBasicType() != EbtSampler && type.getBasicType() != EbtBlock && type.getBasicType() != EbtAtomicUint)
3548             error(loc, "requires block, or sampler/image, or atomic-counter type", "binding", "");
3549         if (type.getBasicType() == EbtSampler) {
3550             int lastBinding = qualifier.layoutBinding;
3551             if (type.isArray())
3552                 lastBinding += type.getArraySize();
3553             if (lastBinding >= resources.maxCombinedTextureImageUnits)
3554                 error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
3555         }
3556         if (type.getBasicType() == EbtAtomicUint) {
3557             if (qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
3558                 error(loc, "atomic_uint binding is too large; see gl_MaxAtomicCounterBindings", "binding", "");
3559                 return;
3560             }
3561         }
3562     }
3563
3564     // atomic_uint
3565     if (type.getBasicType() == EbtAtomicUint) {
3566         if (! type.getQualifier().hasBinding())
3567             error(loc, "layout(binding=X) is required", "atomic_uint", "");
3568     }
3569
3570     // "The offset qualifier can only be used on block members of blocks..."
3571     if (qualifier.hasOffset()) {
3572         if (type.getBasicType() == EbtBlock)
3573             error(loc, "only applies to block members, not blocks", "offset", "");
3574     }
3575
3576     // Image format
3577     if (qualifier.hasFormat()) {
3578         if (! type.isImage())
3579             error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
3580         else {
3581             if (type.getSampler().type == EbtFloat && qualifier.layoutFormat > ElfFloatGuard)
3582                 error(loc, "does not apply to floating point images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
3583             if (type.getSampler().type == EbtInt && (qualifier.layoutFormat < ElfFloatGuard || qualifier.layoutFormat > ElfIntGuard))
3584                 error(loc, "does not apply to signed integer images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
3585             if (type.getSampler().type == EbtUint && qualifier.layoutFormat < ElfIntGuard)
3586                 error(loc, "does not apply to unsigned integer images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
3587
3588             if (profile == EEsProfile) {
3589                 // "Except for image variables qualified with the format qualifiers r32f, r32i, and r32ui, image variables must 
3590                 // specify either memory qualifier readonly or the memory qualifier writeonly."
3591                 if (! (qualifier.layoutFormat == ElfR32f || qualifier.layoutFormat == ElfR32i || qualifier.layoutFormat == ElfR32ui)) {
3592                     if (! qualifier.readonly && ! qualifier.writeonly)
3593                         error(loc, "format requires readonly or writeonly memory qualifier", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
3594                 }
3595             }
3596         }
3597     } else if (type.isImage() && ! qualifier.writeonly)
3598         error(loc, "image variables not declared 'writeonly' must have a format layout qualifier", "", "");
3599 }
3600
3601 // Do layout error checking that can be done within a qualifier proper, not needing to know
3602 // if there are blocks, atomic counters, variables, etc.
3603 void TParseContext::layoutQualifierCheck(TSourceLoc loc, const TQualifier& qualifier)
3604 {
3605     if (qualifier.storage == EvqShared && qualifier.hasLayout())
3606         error(loc, "cannot apply layout qualifiers to a shared variable", "shared", "");
3607
3608     // "It is a compile-time error to use *component* without also specifying the location qualifier (order does not matter)."
3609     if (qualifier.hasComponent() && ! qualifier.hasLocation())
3610         error(loc, "must specify 'location' to use 'component'", "component", "");
3611
3612     if (qualifier.hasAnyLocation()) {
3613
3614         // "As with input layout qualifiers, all shaders except compute shaders 
3615         // allow *location* layout qualifiers on output variable declarations, 
3616         // output block declarations, and output block member declarations."
3617
3618         switch (qualifier.storage) {
3619         case EvqVaryingIn:
3620         {
3621             const char* feature = "location qualifier on input";
3622             if (profile == EEsProfile && version < 310)
3623                 requireStage(loc, EShLangVertex, feature);
3624             else
3625                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
3626             if (language == EShLangVertex) {
3627                 const char* exts[2] = { GL_ARB_separate_shader_objects, GL_ARB_explicit_attrib_location };
3628                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
3629                 profileRequires(loc, EEsProfile, 300, 0, feature);
3630             } else {
3631                 profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
3632                 profileRequires(loc, EEsProfile, 310, 0, feature);
3633             }
3634             break;
3635         }
3636         case EvqVaryingOut:
3637         {
3638             const char* feature = "location qualifier on output";
3639             if (profile == EEsProfile && version < 310)
3640                 requireStage(loc, EShLangFragment, feature);
3641             else
3642                 requireStage(loc, (EShLanguageMask)~EShLangComputeMask, feature);
3643             if (language == EShLangFragment) {
3644                 const char* exts[2] = { GL_ARB_separate_shader_objects, GL_ARB_explicit_attrib_location };
3645                 profileRequires(loc, ~EEsProfile, 330, 2, exts, feature);
3646                 profileRequires(loc, EEsProfile, 300, 0, feature);
3647             } else {
3648                 profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
3649                 profileRequires(loc, EEsProfile, 310, 0, feature);
3650             }
3651             break;
3652         }
3653         case EvqUniform:
3654         case EvqBuffer:
3655         {
3656             const char* feature = "location qualifier on uniform or buffer";
3657             requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, feature);
3658             profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, 0, feature);
3659             profileRequires(loc, EEsProfile, 310, 0, feature);
3660             break;
3661         }
3662         default:
3663             break;
3664         }
3665         if (qualifier.hasIndex()) {
3666             if (qualifier.storage != EvqVaryingOut)
3667                 error(loc, "can only be used on an output", "index", "");
3668             if (! qualifier.hasLocation())
3669                 error(loc, "can only be used with an explicit location", "index", "");
3670         }
3671     }
3672
3673     if (qualifier.hasBinding()) {
3674         if (! qualifier.isUniformOrBuffer())
3675             error(loc, "requires uniform or buffer storage qualifier", "binding", "");
3676     }
3677     if (qualifier.hasStream()) {
3678         if (qualifier.storage != EvqVaryingOut)
3679             error(loc, "can only be used on an output", "stream", "");
3680     }
3681     if (qualifier.hasXfb()) {
3682         if (qualifier.storage != EvqVaryingOut)
3683             error(loc, "can only be used on an output", "xfb layout qualifier", "");
3684     }
3685     if (qualifier.hasUniformLayout()) {
3686         if (! qualifier.isUniformOrBuffer()) {
3687             if (qualifier.hasMatrix() || qualifier.hasPacking())
3688                 error(loc, "matrix or packing qualifiers can only be used on a uniform or buffer", "layout", "");
3689             if (qualifier.hasOffset() || qualifier.hasAlign())
3690                 error(loc, "offset/align can only be used on a uniform or buffer", "layout", "");
3691         }
3692     }
3693 }
3694
3695 // For places that can't have shader-level layout qualifiers
3696 void TParseContext::checkNoShaderLayouts(TSourceLoc loc, const TShaderQualifiers& shaderQualifiers)
3697 {
3698     const char* message = "can only apply to a standalone qualifier";
3699
3700     if (shaderQualifiers.geometry != ElgNone)
3701         error(loc, message, TQualifier::getGeometryString(shaderQualifiers.geometry), "");
3702     if (shaderQualifiers.invocations > 0)
3703         error(loc, message, "invocations", "");
3704     if (shaderQualifiers.vertices > 0) {
3705         if (language == EShLangGeometry)
3706             error(loc, message, "max_vertices", "");
3707         else if (language == EShLangTessControl)
3708             error(loc, message, "vertices", "");
3709         else
3710             assert(0);
3711     }
3712     for (int i = 0; i < 3; ++i) {
3713         if (shaderQualifiers.localSize[i] > 1)
3714             error(loc, message, "local_size", "");
3715     }
3716 }
3717
3718 // Correct and/or advance an object's offset layout qualifier.
3719 void TParseContext::fixOffset(TSourceLoc loc, TSymbol& symbol)
3720 {
3721     const TQualifier& qualifier = symbol.getType().getQualifier();
3722     if (symbol.getType().getBasicType() == EbtAtomicUint) {
3723         if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
3724
3725             // Set the offset
3726             int offset;
3727             if (qualifier.hasOffset())
3728                 offset = qualifier.layoutOffset;
3729             else
3730                 offset = atomicUintOffsets[qualifier.layoutBinding];
3731             symbol.getWritableType().getQualifier().layoutOffset = offset;
3732
3733             // Check for overlap
3734             int numOffsets = 4;
3735             if (symbol.getType().isArray())
3736                 numOffsets *= symbol.getType().getArraySize();
3737             int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
3738             if (repeated >= 0)
3739                 error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
3740
3741             // Bump the default offset
3742             atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
3743         }
3744     }
3745 }
3746
3747 //
3748 // Look up a function name in the symbol table, and make sure it is a function.
3749 //
3750 // Return the function symbol if found, otherwise 0.
3751 //
3752 const TFunction* TParseContext::findFunction(TSourceLoc loc, const TFunction& call, bool& builtIn)
3753 {
3754     const TFunction* function = 0;
3755
3756     if (symbolTable.isFunctionNameVariable(call.getName())) {
3757         error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
3758         return 0;
3759     }
3760
3761     if (profile == EEsProfile || version < 120)
3762         function = findFunctionExact(loc, call, builtIn);
3763     else if (version < 400)
3764         function = findFunction120(loc, call, builtIn);
3765     else
3766         function = findFunction400(loc, call, builtIn);
3767
3768     return function;
3769 }
3770
3771 // Function finding algorithm for ES and desktop 110.
3772 const TFunction* TParseContext::findFunctionExact(TSourceLoc loc, const TFunction& call, bool& builtIn)
3773 {
3774     const TFunction* function = 0;
3775
3776     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
3777     if (symbol == 0) {
3778         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
3779
3780         return 0;
3781     }
3782
3783     return symbol->getAsFunction();
3784 }
3785
3786 // Function finding algorithm for desktop versions 120 through 330.
3787 const TFunction* TParseContext::findFunction120(TSourceLoc loc, const TFunction& call, bool& builtIn)
3788 {
3789     // first, look for an exact match
3790     TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
3791     if (symbol)
3792         return symbol->getAsFunction();
3793
3794     // exact match not found, look through a list of overloaded functions of the same name
3795
3796     // "If no exact match is found, then [implicit conversions] will be applied to find a match. Mismatched types
3797     // on input parameters (in or inout or default) must have a conversion from the calling argument type to the
3798     // formal parameter type. Mismatched types on output parameters (out or inout) must have a conversion
3799     // from the formal parameter type to the calling argument type.  When argument conversions are used to find
3800     // a match, it is a semantic error if there are multiple ways to apply these conversions to make the call match
3801     // more than one function."
3802
3803     const TFunction* candidate = 0;
3804     TVector<TFunction*> candidateList;
3805     symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
3806
3807     int numPossibleMatches = 0;
3808     for (TVector<TFunction*>::const_iterator it = candidateList.begin(); it != candidateList.end(); ++it) {
3809         const TFunction& function = *(*it);
3810
3811         // to even be a potential match, number of arguments has to match
3812         if (call.getParamCount() != function.getParamCount())
3813             continue;
3814
3815         bool possibleMatch = true;
3816         for (int i = 0; i < function.getParamCount(); ++i) {
3817             // same types is easy
3818             if (*function[i].type == *call[i].type)
3819                 continue;
3820
3821             // We have a mismatch in type, see if it is implicitly convertible
3822
3823             if (function[i].type->isArray() || call[i].type->isArray() ||
3824                 ! function[i].type->sameElementShape(*call[i].type))
3825                 possibleMatch = false;
3826             else {
3827                 // do direction-specific checks for conversion of basic type
3828                 if (function[i].type->getQualifier().isParamInput()) {
3829                     if (! intermediate.canImplicitlyPromote(call[i].type->getBasicType(), function[i].type->getBasicType()))
3830                         possibleMatch = false;
3831                 }
3832                 if (function[i].type->getQualifier().isParamOutput()) {
3833                     if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
3834                         possibleMatch = false;
3835                 }
3836             }
3837             if (! possibleMatch)
3838                 break;
3839         }
3840         if (possibleMatch) {
3841             if (candidate) {
3842                 // our second match, meaning ambiguity
3843                 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
3844             } else
3845                 candidate = &function;
3846         }
3847     }
3848
3849     if (candidate == 0)
3850         error(loc, "no matching overloaded function found", call.getName().c_str(), "");
3851
3852     return candidate;
3853 }
3854
3855 // Function finding algorithm for desktop version 400 and above.
3856 const TFunction* TParseContext::findFunction400(TSourceLoc loc, const TFunction& call, bool& builtIn)
3857 {
3858     // TODO: 4.00 functionality: findFunction400()
3859     return findFunction120(loc, call, builtIn);
3860 }
3861
3862 // When a declaration includes a type, but not a variable name, it can be 
3863 // to establish defaults.
3864 void TParseContext::declareTypeDefaults(TSourceLoc loc, const TPublicType& publicType)
3865 {
3866     if (publicType.basicType == EbtAtomicUint && publicType.qualifier.hasBinding() && publicType.qualifier.hasOffset()) {
3867         if (publicType.qualifier.layoutBinding >= (unsigned int)resources.maxAtomicCounterBindings) {
3868             error(loc, "atomic_uint binding is too large", "binding", "");
3869             return;
3870         }
3871         atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
3872         return;
3873     }
3874
3875     if (publicType.qualifier.hasLayout())
3876         warn(loc, "useless application of layout qualifier", "layout", "");
3877 }
3878
3879 //
3880 // Do everything necessary to handle a variable (non-block) declaration.
3881 // Either redeclaring a variable, or making a new one, updating the symbol
3882 // table, and all error checking.
3883 //
3884 // Returns a subtree node that computes an initializer, if needed.
3885 // Returns 0 if there is no code to execute for initialization.
3886 //
3887 TIntermNode* TParseContext::declareVariable(TSourceLoc loc, TString& identifier, const TPublicType& publicType, TArraySizes* arraySizes, TIntermTyped* initializer)
3888 {
3889     TType type(publicType);
3890
3891     if (voidErrorCheck(loc, identifier, type.getBasicType()))
3892         return 0;
3893
3894     if (initializer)        
3895         rValueErrorCheck(loc, "initializer", initializer);
3896     else
3897         nonInitConstCheck(loc, identifier, type);
3898
3899     invariantCheck(loc, type, identifier);
3900     samplerCheck(loc, type, identifier);
3901     atomicUintCheck(loc, type, identifier);
3902
3903     if (identifier != "gl_FragCoord" && (publicType.shaderQualifiers.originUpperLeft || publicType.shaderQualifiers.pixelCenterInteger))
3904         error(loc, "can only apply origin_upper_left and pixel_center_origin to gl_FragCoord", "layout qualifier", "");
3905     if (identifier != "gl_FragDepth" && publicType.shaderQualifiers.layoutDepth != EldNone)
3906         error(loc, "can only apply depth layout to gl_FragDepth", "layout qualifier", "");
3907
3908     // Check for redeclaration of built-ins and/or attempting to declare a reserved name
3909     bool newDeclaration = false;    // true if a new entry gets added to the symbol table
3910     TSymbol* symbol = redeclareBuiltinVariable(loc, identifier, type.getQualifier(), publicType.shaderQualifiers, newDeclaration);
3911     if (! symbol)
3912         reservedErrorCheck(loc, identifier);
3913
3914     inheritGlobalDefaults(type.getQualifier());
3915
3916     // Declare the variable
3917     if (arraySizes || type.isArray()) {
3918         // Arrayness is potentially coming both from the type and from the 
3919         // variable: "int[] a[];" or just one or the other.
3920         // For now, arrays of arrays aren't supported, so it's just one or the
3921         // other.  Move it to the type, so all arrayness is part of the type.
3922         arrayDimCheck(loc, &type, arraySizes);
3923         if (arraySizes)
3924             type.setArraySizes(arraySizes);
3925
3926         // for ES, if size isn't coming from an initializer, it has to be explicitly declared now
3927         if (profile == EEsProfile && ! initializer)
3928             arraySizeRequiredCheck(loc, type.getArraySize());
3929
3930         if (! arrayQualifierError(loc, type.getQualifier()))
3931             declareArray(loc, identifier, type, symbol, newDeclaration);
3932
3933         if (initializer) {
3934             profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "initializer");
3935             profileRequires(loc, EEsProfile, 300, 0, "initializer");
3936         }
3937     } else {
3938         // non-array case
3939         if (! symbol)
3940             symbol = declareNonArray(loc, identifier, type, newDeclaration);
3941         else if (type != symbol->getType())
3942             error(loc, "cannot change the type of", "redeclaration", symbol->getName().c_str());
3943     }
3944
3945     if (! symbol)
3946         return 0;
3947
3948     // Deal with initializer
3949     TIntermNode* initNode = 0;
3950     if (symbol && initializer) {
3951         TVariable* variable = symbol->getAsVariable();
3952         if (! variable) {
3953             error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
3954             return 0;
3955         }
3956         initNode = executeInitializer(loc, identifier, initializer, variable);
3957     }
3958
3959     // look for errors in layout qualifier use
3960     layoutObjectCheck(loc, *symbol);
3961     fixOffset(loc, *symbol);
3962
3963     // see if it's a linker-level object to track
3964     if (newDeclaration && symbolTable.atGlobalLevel())
3965         intermediate.addSymbolLinkageNode(linkage, *symbol);
3966
3967     return initNode;
3968 }
3969
3970 // Pick up global defaults from the provide global defaults into dst.
3971 void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
3972 {
3973     if (dst.storage == EvqVaryingOut) {
3974         if (! dst.hasStream() && language == EShLangGeometry)
3975             dst.layoutStream = globalOutputDefaults.layoutStream;
3976         if (! dst.hasXfbBuffer())
3977             dst.layoutXfbBuffer = globalOutputDefaults.layoutXfbBuffer;
3978     }
3979 }
3980
3981 //
3982 // Make an internal-only variable whose name is for debug purposes only
3983 // and won't be searched for.  Callers will only use the return value to use
3984 // the variable, not the name to look it up.  It is okay if the name
3985 // is the same as other names; there won't be any conflict.
3986 //
3987 TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
3988 {
3989     TString* nameString = new TString(name);
3990     TSourceLoc loc = {0, 0};
3991     TVariable* variable = new TVariable(nameString, type);
3992     symbolTable.makeInternalVariable(*variable);
3993
3994     return variable;
3995 }
3996
3997 //
3998 // Declare a non-array variable, the main point being there is no redeclaration
3999 // for resizing allowed.
4000 //
4001 // Return the successfully declared variable.
4002 //
4003 TVariable* TParseContext::declareNonArray(TSourceLoc loc, TString& identifier, TType& type, bool& newDeclaration)
4004 {
4005     // make a new variable
4006     TVariable* variable = new TVariable(&identifier, type);
4007
4008     ioArrayCheck(loc, type, identifier);
4009     // add variable to symbol table
4010     if (! symbolTable.insert(*variable)) {
4011         error(loc, "redefinition", variable->getName().c_str(), "");
4012         return 0;
4013     } else {
4014         newDeclaration = true;
4015         return variable;
4016     }
4017 }
4018
4019 //
4020 // Handle all types of initializers from the grammar.
4021 //
4022 // Returning 0 just means there is no code to execute to handle the
4023 // initializer, which will, for example, be the case for constant initializers.
4024 //
4025 TIntermNode* TParseContext::executeInitializer(TSourceLoc loc, TString& identifier,
4026                                                TIntermTyped* initializer, TVariable* variable)
4027 {
4028     //
4029     // Identifier must be of type constant, a global, or a temporary, and
4030     // starting at version 120, desktop allows uniforms to have initializers.
4031     //
4032     TStorageQualifier qualifier = variable->getType().getQualifier().storage;
4033     if (! (qualifier == EvqTemporary || qualifier == EvqGlobal || qualifier == EvqConst ||
4034            (qualifier == EvqUniform && profile != EEsProfile && version >= 120))) {
4035         error(loc, " cannot initialize this type of qualifier ", variable->getType().getStorageQualifierString(), "");
4036         return 0;
4037     }
4038     arrayObjectCheck(loc, variable->getType(), "array initializer");
4039
4040     //
4041     // If the initializer was from braces { ... }, we convert the whole subtree to a
4042     // constructor-style subtree, allowing the rest of the code to operate
4043     // identically for both kinds of initializers.
4044     //
4045     initializer = convertInitializerList(loc, variable->getType(), initializer);
4046     if (! initializer) {
4047         // error recovery; don't leave const without constant values
4048         if (qualifier == EvqConst)
4049             variable->getWritableType().getQualifier().storage = EvqTemporary;
4050         return 0;
4051     }
4052
4053     // Fix arrayness if variable is unsized, getting size from the initializer
4054     if (initializer->getType().isArray() && initializer->getType().isExplicitlySizedArray() &&
4055         variable->getType().isImplicitlySizedArray())
4056         variable->getWritableType().changeArraySize(initializer->getType().getArraySize());
4057
4058     // Uniform and global consts require a constant initializer
4059     if (qualifier == EvqUniform && initializer->getType().getQualifier().storage != EvqConst) {
4060         error(loc, "uniform initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
4061         variable->getWritableType().getQualifier().storage = EvqTemporary;
4062         return 0;
4063     }
4064     if (qualifier == EvqConst && symbolTable.atGlobalLevel() && initializer->getType().getQualifier().storage != EvqConst) {
4065         error(loc, "global const initializers must be constant", "=", "'%s'", variable->getType().getCompleteString().c_str());
4066         variable->getWritableType().getQualifier().storage = EvqTemporary;
4067         return 0;
4068     }
4069
4070     // Const variables require a constant initializer, depending on version
4071     if (qualifier == EvqConst) {
4072         if (initializer->getType().getQualifier().storage != EvqConst) {
4073             const char* initFeature = "non-constant initializer";
4074             requireProfile(loc, ~EEsProfile, initFeature);
4075             profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, initFeature);
4076             variable->getWritableType().getQualifier().storage = EvqConstReadOnly;
4077             qualifier = EvqConstReadOnly;
4078         }
4079     }
4080
4081     if (qualifier == EvqConst || qualifier == EvqUniform) {
4082         // Compile-time tagging of the variable with it's constant value...
4083
4084         initializer = intermediate.addConversion(EOpAssign, variable->getType(), initializer);
4085         if (! initializer || ! initializer->getAsConstantUnion() || variable->getType() != initializer->getType()) {
4086             error(loc, "non-matching or non-convertible constant type for const initializer",
4087                   variable->getType().getStorageQualifierString(), "");
4088             variable->getWritableType().getQualifier().storage = EvqTemporary;
4089             return 0;
4090         }
4091
4092         variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
4093     } else {
4094         // normal assigning of a value to a variable...
4095         TIntermSymbol* intermSymbol = intermediate.addSymbol(*variable, loc);
4096         TIntermNode* initNode = intermediate.addAssign(EOpAssign, intermSymbol, initializer, loc);
4097         if (! initNode)
4098             assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
4099
4100         return initNode;
4101     }
4102
4103     return 0;
4104 }
4105
4106 //
4107 // Reprocess any initializer-list { ... } parts of the initializer.
4108 // Need to heirarchically assign correct types and implicit
4109 // conversions. Will do this mimicking the same process used for
4110 // creating a constructor-style initializer, ensuring we get the
4111 // same form.
4112 //
4113 TIntermTyped* TParseContext::convertInitializerList(TSourceLoc loc, const TType& type, TIntermTyped* initializer)
4114 {
4115     // Will operate recursively.  Once a subtree is found that is constructor style,
4116     // everything below it is already good: Only the "top part" of the initializer
4117     // can be an initializer list, where "top part" can extend for several (or all) levels.
4118
4119     // see if we have bottomed out in the tree within the initializer-list part
4120     TIntermAggregate* initList = initializer->getAsAggregate();
4121     if (! initList || initList->getOp() != EOpNull)
4122         return initializer;
4123
4124     // Of the initializer-list set of nodes, need to process bottom up,
4125     // so recurse deep, then process on the way up.
4126
4127     // Go down the tree here...
4128     if (type.isArray()) {
4129         // The type's array might be unsized, which could be okay, so base sizes on the size of the aggregate.
4130         // Later on, initializer execution code will deal with array size logic.
4131         TType arrayType;
4132         arrayType.shallowCopy(type);
4133         arrayType.setArraySizes(type);
4134         arrayType.changeArraySize((int)initList->getSequence().size());
4135         TType elementType(arrayType, 0); // dereferenced type
4136         for (size_t i = 0; i < initList->getSequence().size(); ++i) {
4137             initList->getSequence()[i] = convertInitializerList(loc, elementType, initList->getSequence()[i]->getAsTyped());
4138             if (initList->getSequence()[i] == 0)
4139                 return 0;
4140         }
4141
4142         return addConstructor(loc, initList, arrayType, mapTypeToConstructorOp(arrayType));
4143     } else if (type.isStruct()) {
4144         if (type.getStruct()->size() != initList->getSequence().size()) {
4145             error(loc, "wrong number of structure members", "initializer list", "");
4146             return 0;
4147         }
4148         for (size_t i = 0; i < type.getStruct()->size(); ++i) {
4149             initList->getSequence()[i] = convertInitializerList(loc, *(*type.getStruct())[i].type, initList->getSequence()[i]->getAsTyped());
4150             if (initList->getSequence()[i] == 0)
4151                 return 0;
4152         }
4153     } else if (type.isMatrix()) {
4154         if (type.getMatrixCols() != initList->getSequence().size()) {
4155             error(loc, "wrong number of matrix columns:", "initializer list", type.getCompleteString().c_str());
4156             return 0;
4157         }
4158         TType vectorType(type, 0); // dereferenced type
4159         for (int i = 0; i < type.getMatrixCols(); ++i) {
4160             initList->getSequence()[i] = convertInitializerList(loc, vectorType, initList->getSequence()[i]->getAsTyped());
4161             if (initList->getSequence()[i] == 0)
4162                 return 0;
4163         }
4164     } else if (type.isVector()) {
4165         if (type.getVectorSize() != initList->getSequence().size()) {
4166             error(loc, "wrong vector size (or rows in a matrix column):", "initializer list", type.getCompleteString().c_str());
4167             return 0;
4168         }
4169     } else {
4170         error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
4171         return 0;
4172     }
4173
4174     // now that the subtree is processed, process this node
4175     return addConstructor(loc, initList, type, mapTypeToConstructorOp(type));
4176 }
4177
4178 //
4179 // Test for the correctness of the parameters passed to various constructor functions
4180 // and also convert them to the right data type, if allowed and required.
4181 //
4182 // Returns 0 for an error or the constructed node (aggregate or typed) for no error.
4183 //
4184 TIntermTyped* TParseContext::addConstructor(TSourceLoc loc, TIntermNode* node, const TType& type, TOperator op)
4185 {
4186     if (node == 0 || node->getAsTyped() == 0)
4187         return 0;
4188     rValueErrorCheck(loc, "constructor", node->getAsTyped());
4189
4190     TIntermAggregate* aggrNode = node->getAsAggregate();
4191
4192     TTypeList::const_iterator memberTypes;
4193     if (op == EOpConstructStruct)
4194         memberTypes = type.getStruct()->begin();
4195
4196     TType elementType;
4197     elementType.shallowCopy(type);
4198     if (type.isArray())
4199         elementType.dereference();
4200
4201     bool singleArg;
4202     if (aggrNode) {
4203         if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1)
4204             singleArg = true;
4205         else
4206             singleArg = false;
4207     } else
4208         singleArg = true;
4209
4210     TIntermTyped *newNode;
4211     if (singleArg) {
4212         // If structure constructor or array constructor is being called
4213         // for only one parameter inside the structure, we need to call constructStruct function once.
4214         if (type.isArray())
4215             newNode = constructStruct(node, elementType, 1, node->getLoc());
4216         else if (op == EOpConstructStruct)
4217             newNode = constructStruct(node, *(*memberTypes).type, 1, node->getLoc());
4218         else
4219             newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
4220
4221         if (newNode && (type.isArray() || op == EOpConstructStruct))
4222             newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
4223
4224         return newNode;
4225     }
4226
4227     //
4228     // Handle list of arguments.
4229     //
4230     TIntermSequence &sequenceVector = aggrNode->getSequence();    // Stores the information about the parameter to the constructor
4231     // if the structure constructor contains more than one parameter, then construct
4232     // each parameter
4233
4234     int paramCount = 0;  // keeps a track of the constructor parameter number being checked
4235
4236     // for each parameter to the constructor call, check to see if the right type is passed or convert them
4237     // to the right type if possible (and allowed).
4238     // for structure constructors, just check if the right type is passed, no conversion is allowed.
4239
4240     for (TIntermSequence::iterator p = sequenceVector.begin();
4241                                    p != sequenceVector.end(); p++, paramCount++) {
4242         if (type.isArray())
4243             newNode = constructStruct(*p, elementType, paramCount+1, node->getLoc());
4244         else if (op == EOpConstructStruct)
4245             newNode = constructStruct(*p, *(memberTypes[paramCount]).type, paramCount+1, node->getLoc());
4246         else
4247             newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
4248
4249         if (newNode)
4250             *p = newNode;
4251         else
4252             return 0;
4253     }
4254
4255     TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
4256
4257     return constructor;
4258 }
4259
4260 // Function for constructor implementation. Calls addUnaryMath with appropriate EOp value
4261 // for the parameter to the constructor (passed to this function). Essentially, it converts
4262 // the parameter types correctly. If a constructor expects an int (like ivec2) and is passed a
4263 // float, then float is converted to int.
4264 //
4265 // Returns 0 for an error or the constructed node.
4266 //
4267 TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, TSourceLoc loc, bool subset)
4268 {
4269     TIntermTyped* newNode;
4270     TOperator basicOp;
4271
4272     //
4273     // First, convert types as needed.
4274     //
4275     switch (op) {
4276     case EOpConstructVec2:
4277     case EOpConstructVec3:
4278     case EOpConstructVec4:
4279     case EOpConstructMat2x2:
4280     case EOpConstructMat2x3:
4281     case EOpConstructMat2x4:
4282     case EOpConstructMat3x2:
4283     case EOpConstructMat3x3:
4284     case EOpConstructMat3x4:
4285     case EOpConstructMat4x2:
4286     case EOpConstructMat4x3:
4287     case EOpConstructMat4x4:
4288     case EOpConstructFloat:
4289         basicOp = EOpConstructFloat;
4290         break;
4291
4292     case EOpConstructDVec2:
4293     case EOpConstructDVec3:
4294     case EOpConstructDVec4:
4295     case EOpConstructDMat2x2:
4296     case EOpConstructDMat2x3:
4297     case EOpConstructDMat2x4:
4298     case EOpConstructDMat3x2:
4299     case EOpConstructDMat3x3:
4300     case EOpConstructDMat3x4:
4301     case EOpConstructDMat4x2:
4302     case EOpConstructDMat4x3:
4303     case EOpConstructDMat4x4:
4304     case EOpConstructDouble:
4305         basicOp = EOpConstructDouble;
4306         break;
4307
4308     case EOpConstructIVec2:
4309     case EOpConstructIVec3:
4310     case EOpConstructIVec4:
4311     case EOpConstructInt:
4312         basicOp = EOpConstructInt;
4313         break;
4314
4315     case EOpConstructUVec2:
4316     case EOpConstructUVec3:
4317     case EOpConstructUVec4:
4318     case EOpConstructUint:
4319         basicOp = EOpConstructUint;
4320         break;
4321
4322     case EOpConstructBVec2:
4323     case EOpConstructBVec3:
4324     case EOpConstructBVec4:
4325     case EOpConstructBool:
4326         basicOp = EOpConstructBool;
4327         break;
4328
4329     default:
4330         error(loc, "unsupported construction", "", "");
4331
4332         return 0;
4333     }
4334     newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
4335     if (newNode == 0) {
4336         error(loc, "can't convert", "constructor", "");
4337         return 0;
4338     }
4339
4340     //
4341     // Now, if there still isn't an operation to do the construction, and we need one, add one.
4342     //
4343
4344     // Otherwise, skip out early.
4345     if (subset || (newNode != node && newNode->getType() == type))
4346         return newNode;
4347
4348     // setAggregateOperator will insert a new node for the constructor, as needed.
4349     return intermediate.setAggregateOperator(newNode, op, type, loc);
4350 }
4351
4352 // This function tests for the type of the parameters to the structures constructors. Raises
4353 // an error message if the expected type does not match the parameter passed to the constructor.
4354 //
4355 // Returns 0 for an error or the input node itself if the expected and the given parameter types match.
4356 //
4357 TIntermTyped* TParseContext::constructStruct(TIntermNode* node, const TType& type, int paramCount, TSourceLoc loc)
4358 {
4359     TIntermTyped* converted = intermediate.addConversion(EOpConstructStruct, type, node->getAsTyped());
4360     if (! converted || converted->getType() != type) {
4361         error(loc, "", "constructor", "cannot convert parameter %d from '%s' to '%s'", paramCount,
4362               node->getAsTyped()->getType().getCompleteString().c_str(), type.getCompleteString().c_str());
4363
4364         return 0;
4365     }
4366
4367     return converted;
4368 }
4369
4370 //
4371 // Do everything needed to add an interface block.
4372 //
4373 void TParseContext::declareBlock(TSourceLoc loc, TTypeList& typeList, const TString* instanceName, TArraySizes* arraySizes)
4374 {
4375     if (profile == EEsProfile && arraySizes)
4376         arraySizeRequiredCheck(loc, arraySizes->getSize());
4377
4378     switch (currentBlockQualifier.storage) {
4379     case EvqUniform:
4380         profileRequires(loc, EEsProfile, 300, 0, "uniform block");
4381         profileRequires(loc, ENoProfile, 140, 0, "uniform block");
4382         break;
4383     case EvqBuffer:
4384         requireProfile(loc, EEsProfile | ECoreProfile | ECompatibilityProfile, "buffer block");
4385         profileRequires(loc, ECoreProfile | ECompatibilityProfile, 430, 0, "buffer block");
4386         profileRequires(loc, EEsProfile, 310, 0, "buffer block");
4387         break;
4388     case EvqVaryingIn:
4389         requireProfile(loc, ~EEsProfile, "input block");
4390         profileRequires(loc, ~EEsProfile, 150, GL_ARB_separate_shader_objects, "input block");
4391         if (language == EShLangVertex)
4392             error(loc, "cannot declare an input block in a vertex shader", "in", "");
4393         break;
4394     case EvqVaryingOut:
4395         requireProfile(loc, ~EEsProfile, "output block");
4396         profileRequires(loc, ~EEsProfile, 150, GL_ARB_separate_shader_objects, "output block");
4397         if (language == EShLangFragment)
4398             error(loc, "cannot declare an output block in a fragment shader", "out", "");
4399         break;
4400     default:
4401         error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
4402         return;
4403     }
4404
4405     arrayDimCheck(loc, arraySizes, 0);
4406
4407     // fix and check for member storage qualifiers and types that don't belong within a block
4408     for (unsigned int member = 0; member < typeList.size(); ++member) {
4409         TType& memberType = *typeList[member].type;
4410         TQualifier& memberQualifier = memberType.getQualifier();
4411         TSourceLoc memberLoc = typeList[member].loc;
4412         pipeInOutFix(memberLoc, memberQualifier);
4413         if (memberQualifier.storage != EvqTemporary && memberQualifier.storage != EvqGlobal && memberQualifier.storage != currentBlockQualifier.storage)
4414             error(memberLoc, "member storage qualifier cannot contradict block storage qualifier", memberType.getFieldName().c_str(), "");
4415         memberQualifier.storage = currentBlockQualifier.storage;
4416         if ((currentBlockQualifier.storage == EvqUniform || currentBlockQualifier.storage == EvqBuffer) && (memberQualifier.isInterpolation() || memberQualifier.isAuxiliary()))
4417             error(memberLoc, "member of uniform or buffer block cannot have an auxiliary or interpolation qualifier", memberType.getFieldName().c_str(), "");
4418         if (memberType.isRuntimeSizedArray() && member < typeList.size() - 1)
4419             error(memberLoc, "only the last member of a buffer block can be run-time sized", memberType.getFieldName().c_str(), "");
4420         if (memberType.isImplicitlySizedArray())
4421             requireProfile(memberLoc, ~EEsProfile, "implicitly-sized array in a block");
4422         if (memberQualifier.hasOffset()) {
4423             requireProfile(memberLoc, ~EEsProfile, "offset on block member");
4424             profileRequires(memberLoc, ~EEsProfile, 440, GL_ARB_enhanced_layouts, "offset on block member");
4425         }
4426
4427         TBasicType basicType = memberType.getBasicType();
4428         if (basicType == EbtSampler)
4429             error(memberLoc, "member of block cannot be a sampler type", typeList[member].type->getFieldName().c_str(), "");
4430     }
4431
4432     // This might be a redeclaration of a built-in block.  If so, redeclareBuiltinBlock() will
4433     // do all the rest.
4434     if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
4435         redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
4436         return;
4437     }
4438
4439     // Not a redeclaration of a built-in; check that all names are user names.
4440     reservedErrorCheck(loc, *blockName);
4441     if (instanceName)
4442         reservedErrorCheck(loc, *instanceName);
4443     for (unsigned int member = 0; member < typeList.size(); ++member)
4444         reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
4445
4446     // Make default block qualification, and adjust the member qualifications
4447
4448     TQualifier defaultQualification;
4449     switch (currentBlockQualifier.storage) {
4450     case EvqUniform:    defaultQualification = globalUniformDefaults;    break;
4451     case EvqBuffer:     defaultQualification = globalBufferDefaults;     break;
4452     case EvqVaryingIn:  defaultQualification = globalInputDefaults;      break;
4453     case EvqVaryingOut: defaultQualification = globalOutputDefaults;     break;
4454     default:            defaultQualification.clear();                    break;
4455     }
4456
4457     // fix and check for member layout qualifiers
4458
4459     mergeObjectLayoutQualifiers(loc, defaultQualification, currentBlockQualifier, true);
4460
4461     // "The offset qualifier can only be used on block members of blocks declared with std140 or std430 layouts."
4462     // "The align qualifier can only be used on blocks or block members, and only for blocks declared with std140 or std430 layouts."
4463     if (currentBlockQualifier.hasAlign() || currentBlockQualifier.hasAlign()) {
4464         if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430) {
4465             error(loc, "can only be used with std140 or std430 layout packing", "offset/align", "");
4466             defaultQualification.layoutAlign = -1;
4467         }
4468     }
4469
4470     bool memberWithLocation = false;
4471     bool memberWithoutLocation = false;
4472     for (unsigned int member = 0; member < typeList.size(); ++member) {
4473         TQualifier& memberQualifier = typeList[member].type->getQualifier();
4474         TSourceLoc memberLoc = typeList[member].loc;
4475         if (memberQualifier.hasStream()) {
4476             if (defaultQualification.layoutStream != memberQualifier.layoutStream)
4477                 error(memberLoc, "member cannot contradict block", "stream", "");
4478         }
4479
4480         // "This includes a block's inheritance of the 
4481         // current global default buffer, a block member's inheritance of the block's 
4482         // buffer, and the requirement that any *xfb_buffer* declared on a block 
4483         // member must match the buffer inherited from the block."
4484         if (memberQualifier.hasXfbBuffer()) {
4485             if (defaultQualification.layoutXfbBuffer != memberQualifier.layoutXfbBuffer)
4486                 error(memberLoc, "member cannot contradict block (or what block inherited from global)", "xfb_buffer", "");
4487         }
4488
4489         if (memberQualifier.hasPacking())
4490             error(memberLoc, "member of block cannot have a packing layout qualifier", typeList[member].type->getFieldName().c_str(), "");
4491         if (memberQualifier.hasLocation()) {
4492             const char* feature = "location on block member";
4493             switch (currentBlockQualifier.storage) {
4494             case EvqVaryingIn:
4495             case EvqVaryingOut:
4496                 requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile, feature);
4497                 profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, feature);
4498                 memberWithLocation = true;
4499                 break;
4500             default:
4501                 error(memberLoc, "can only use in an in/out block", feature, "");
4502                 break;
4503             }
4504         } else
4505             memberWithoutLocation = true;
4506         if (memberQualifier.hasAlign()) {
4507             if (defaultQualification.layoutPacking != ElpStd140 && defaultQualification.layoutPacking != ElpStd430)
4508                 error(memberLoc, "can only be used with std140 or std430 layout packing", "align", "");
4509         }
4510
4511         TQualifier newMemberQualification = defaultQualification;
4512         mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
4513         memberQualifier = newMemberQualification;
4514     }
4515
4516     // Process the members
4517     fixBlockLocations(loc, currentBlockQualifier, typeList, memberWithLocation, memberWithoutLocation);
4518     fixBlockXfbOffsets(loc, currentBlockQualifier, typeList);
4519     fixBlockUniformOffsets(loc, currentBlockQualifier, typeList);
4520     for (unsigned int member = 0; member < typeList.size(); ++member)
4521         layoutTypeCheck(typeList[member].loc, *typeList[member].type);
4522
4523     // reverse merge, so that currentBlockQualifier now has all layout information
4524     // (can't use defaultQualification directly, it's missing other non-layout-default-class qualifiers)
4525     mergeObjectLayoutQualifiers(loc, currentBlockQualifier, defaultQualification, true);
4526
4527     //
4528     // Build and add the interface block as a new type named 'blockName'
4529     //
4530
4531     TType blockType(&typeList, *blockName, currentBlockQualifier);
4532     if (arraySizes)
4533         blockType.setArraySizes(arraySizes);
4534     else
4535         ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
4536
4537     //
4538     // Don't make a user-defined type out of block name; that will cause an error
4539     // if the same block name gets reused in a different interface.
4540     //
4541     // "Block names have no other use within a shader
4542     // beyond interface matching; it is a compile-time error to use a block name at global scope for anything
4543     // other than as a block name (e.g., use of a block name for a global variable name or function name is
4544     // currently reserved)."
4545     //
4546     // Use the symbol table to prevent normal reuse of the block's name, as a variable entry,
4547     // whose type is EbtBlock, but without all the structure; that will come from the type
4548     // the instances point to.
4549     //
4550     TType blockNameType(EbtBlock, blockType.getQualifier().storage);
4551     TVariable* blockNameVar = new TVariable(blockName, blockNameType);
4552     if (! symbolTable.insert(*blockNameVar)) {
4553         TSymbol* existingName = symbolTable.find(*blockName);
4554         if (existingName->getType().getBasicType() == EbtBlock) {
4555             if (existingName->getType().getQualifier().storage == blockType.getQualifier().storage) {
4556                 error(loc, "Cannot reuse block name within the same interface:", blockName->c_str(), blockType.getStorageQualifierString());
4557                 return;
4558             }
4559         } else {
4560             error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
4561             return;
4562         }
4563     }
4564
4565     // Add the variable, as anonymous or named instanceName.
4566     // Make an anonymous variable if no name was provided.
4567     if (! instanceName)
4568         instanceName = NewPoolTString("");
4569
4570     TVariable& variable = *new TVariable(instanceName, blockType);
4571     if (! symbolTable.insert(variable)) {
4572         if (*instanceName == "")
4573             error(loc, "nameless block contains a member that already has a name at global scope", blockName->c_str(), "");
4574         else
4575             error(loc, "block instance name redefinition", variable.getName().c_str(), "");
4576
4577         return;
4578     }
4579
4580     // Check for general layout qualifier errors
4581     layoutObjectCheck(loc, variable);
4582
4583     if (isIoResizeArray(blockType)) {
4584         ioArraySymbolResizeList.push_back(&variable);
4585         checkIoArraysConsistency(loc, true);
4586     } else
4587         fixIoArraySize(loc, variable.getWritableType());
4588
4589     // Save it in the AST for linker use.
4590     intermediate.addSymbolLinkageNode(linkage, variable);
4591 }
4592
4593 //
4594 // "For a block, this process applies to the entire block, or until the first member 
4595 // is reached that has a location layout qualifier. When a block member is declared with a location 
4596 // qualifier, its location comes from that qualifier: The member's location qualifier overrides the block-level
4597 // declaration. Subsequent members are again assigned consecutive locations, based on the newest location, 
4598 // until the next member declared with a location qualifier. The values used for locations do not have to be 
4599 // declared in increasing order."
4600 void TParseContext::fixBlockLocations(TSourceLoc loc, TQualifier& qualifier, TTypeList& typeList, bool memberWithLocation, bool memberWithoutLocation)
4601 {
4602     // "If a block has no block-level location layout qualifier, it is required that either all or none of its members 
4603     // have a location layout qualifier, or a compile-time error results."
4604     if (! qualifier.hasLocation() && memberWithLocation && memberWithoutLocation)
4605         error(loc, "either the block needs a location, or all members need a location, or no members have a location", "location", "");
4606     else {
4607         if (memberWithLocation) {
4608             // remove any block-level location and make it per *every* member
4609             int nextLocation;  // by the rule above, initial value is not relevant
4610             if (qualifier.hasAnyLocation()) {
4611                 nextLocation = qualifier.layoutLocation;
4612                 qualifier.layoutLocation = TQualifier::layoutLocationEnd;
4613                 if (qualifier.hasComponent()) {
4614                     // "It is a compile-time error to apply the *component* qualifier to a ... block"
4615                     error(loc, "cannot apply to a block", "component", "");
4616                 }
4617                 if (qualifier.hasIndex()) {
4618                     error(loc, "cannot apply to a block", "index", "");
4619                 }
4620             }
4621             for (unsigned int member = 0; member < typeList.size(); ++member) {
4622                 TQualifier& memberQualifier = typeList[member].type->getQualifier();
4623                 TSourceLoc memberLoc = typeList[member].loc;
4624                 if (! memberQualifier.hasLocation()) {
4625                     if (nextLocation >= TQualifier::layoutLocationEnd)
4626                         error(memberLoc, "location is too large", "location", "");
4627                     memberQualifier.layoutLocation = nextLocation;
4628                     memberQualifier.layoutComponent = 0;
4629                 }
4630                 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(*typeList[member].type);
4631             }
4632         }
4633     }
4634 }
4635
4636 void TParseContext::fixBlockXfbOffsets(TSourceLoc loc, TQualifier& qualifier, TTypeList& typeList)
4637 {
4638     // "If a block is qualified with xfb_offset, all its 
4639     // members are assigned transform feedback buffer offsets. If a block is not qualified with xfb_offset, any 
4640     // members of that block not qualified with an xfb_offset will not be assigned transform feedback buffer 
4641     // offsets."
4642
4643     if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
4644         return;
4645
4646     int nextOffset = qualifier.layoutXfbOffset;
4647     for (unsigned int member = 0; member < typeList.size(); ++member) {
4648         TQualifier& memberQualifier = typeList[member].type->getQualifier();
4649         bool containsDouble = false;
4650         int memberSize = intermediate.computeTypeXfbSize(*typeList[member].type, containsDouble);
4651         // see if we need to auto-assign an offset to this member
4652         if (! memberQualifier.hasXfbOffset()) {
4653             // "if applied to an aggregate containing a double, the offset must also be a multiple of 8"
4654             if (containsDouble)
4655                 RoundToPow2(nextOffset, 8);
4656             memberQualifier.layoutXfbOffset = nextOffset;
4657         } else
4658             nextOffset = memberQualifier.layoutXfbOffset;
4659         nextOffset += memberSize;
4660     }
4661
4662     // The above gave all block members an offset, so we can take it off the block now,
4663     // which will avoid double counting the offset usage.
4664     qualifier.layoutXfbOffset = TQualifier::layoutXfbOffsetEnd;
4665 }
4666
4667 // Calculate and save the offset of each block member, using the recursively 
4668 // defined block offset rules and the user-provided offset and align.
4669 //
4670 // Also, compute and save the total size of the block. For the block's size, arrayness 
4671 // is not taken into account, as each element is backed by a separate buffer.
4672 //
4673 void TParseContext::fixBlockUniformOffsets(TSourceLoc loc, TQualifier& qualifier, TTypeList& typeList)
4674 {
4675     if (! qualifier.isUniformOrBuffer())
4676         return;
4677     if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
4678         return;
4679
4680     int offset = 0;
4681     int memberSize;
4682     for (unsigned int member = 0; member < typeList.size(); ++member) {
4683         TQualifier& memberQualifier = typeList[member].type->getQualifier();
4684         TSourceLoc memberLoc = typeList[member].loc;
4685
4686         // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
4687         
4688         int memberAlignment = intermediate.getBaseAlignment(*typeList[member].type, memberSize, qualifier.layoutPacking == ElpStd140);
4689         if (memberQualifier.hasOffset()) {
4690             // "The specified offset must be a multiple 
4691             // of the base alignment of the type of the block member it qualifies, or a compile-time error results."
4692             if (! IsMultipleOfPow2(memberQualifier.layoutOffset, memberAlignment))
4693                 error(memberLoc, "must be a multiple of the member's alignment", "offset", "");
4694
4695             // "It is a compile-time error to specify an offset that is smaller than the offset of the previous 
4696             // member in the block or that lies within the previous member of the block"
4697             if (memberQualifier.layoutOffset < offset)
4698                 error(memberLoc, "cannot lie in previous members", "offset", "");
4699
4700             // "The offset qualifier forces the qualified member to start at or after the specified 
4701             // integral-constant expression, which will be its byte offset from the beginning of the buffer. 
4702             // "The actual offset of a member is computed as 
4703             // follows: If offset was declared, start with that offset, otherwise start with the next available offset."
4704             offset = std::max(offset, memberQualifier.layoutOffset);
4705         }
4706
4707         // "The actual alignment of a member will be the greater of the specified align alignment and the standard 
4708         // (e.g., std140) base alignment for the member's type."
4709         if (memberQualifier.hasAlign())
4710             memberAlignment = std::max(memberAlignment, memberQualifier.layoutAlign);
4711
4712         // "If the resulting offset is not a multiple of the actual alignment,
4713         // increase it to the first offset that is a multiple of 
4714         // the actual alignment."
4715         RoundToPow2(offset, memberAlignment);
4716         typeList[member].type->getQualifier().layoutOffset = offset;
4717         offset += memberSize;
4718     }
4719 }
4720
4721 // For an identifier that is already declared, add more qualification to it.
4722 void TParseContext::addQualifierToExisting(TSourceLoc loc, TQualifier qualifier, const TString& identifier)
4723 {
4724     TSymbol* symbol = symbolTable.find(identifier);
4725     if (! symbol) {
4726         error(loc, "identifier not previously declared", identifier.c_str(), "");
4727         return;
4728     }
4729     if (symbol->getAsFunction()) {
4730         error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
4731         return;
4732     }
4733
4734     if (qualifier.isAuxiliary() ||
4735         qualifier.isMemory() ||
4736         qualifier.isInterpolation() ||
4737         qualifier.hasLayout() ||
4738         qualifier.storage != EvqTemporary ||
4739         qualifier.precision != EpqNone) {
4740         error(loc, "cannot add storage, auxiliary, memory, interpolation, layout, or precision qualifier to an existing variable", identifier.c_str(), "");
4741         return;
4742     }
4743
4744     // For read-only built-ins, add a new symbol for holding the modified qualifier.
4745     // This will bring up an entire block, if a block type has to be modified (e.g., gl_Position inside a block)
4746     if (symbol->isReadOnly())
4747         symbol = symbolTable.copyUp(symbol);
4748
4749     if (qualifier.invariant) {
4750         if (intermediate.inIoAccessed(identifier))
4751             error(loc, "cannot change qualification after use", "invariant", "");
4752         symbol->getWritableType().getQualifier().invariant = true;
4753         invariantCheck(loc, symbol->getType(), identifier);
4754     } else
4755         warn(loc, "unknown requalification", "", "");
4756 }
4757
4758 void TParseContext::addQualifierToExisting(TSourceLoc loc, TQualifier qualifier, TIdentifierList& identifiers)
4759 {
4760     for (unsigned int i = 0; i < identifiers.size(); ++i)
4761         addQualifierToExisting(loc, qualifier, *identifiers[i]);
4762 }
4763
4764 void TParseContext::invariantCheck(TSourceLoc loc, const TType& type, const TString& identifier)
4765 {
4766     if (! type.getQualifier().invariant)
4767         return;
4768
4769     bool pipeOut = type.getQualifier().isPipeOutput();
4770     bool pipeIn = type.getQualifier().isPipeInput();
4771     if (version >= 300 || profile != EEsProfile && version >= 420) {
4772         if (! pipeOut)
4773             error(loc, "can only apply to an output:", "invariant", identifier.c_str());
4774     } else {
4775         if ((language == EShLangVertex && pipeIn) || (! pipeOut && ! pipeIn))
4776             error(loc, "can only apply to an output or an input in a non-vertex stage\n", "invariant", "");
4777     }
4778 }
4779
4780 //
4781 // Updating default qualifier for the case of a declaration with just a qualifier,
4782 // no type, block, or identifier.
4783 //
4784 void TParseContext::updateStandaloneQualifierDefaults(TSourceLoc loc, const TPublicType& publicType)
4785 {
4786     if (publicType.shaderQualifiers.vertices) {
4787         assert(language == EShLangTessControl || language == EShLangGeometry);
4788         const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
4789
4790         if (publicType.qualifier.storage != EvqVaryingOut)
4791             error(loc, "can only apply to 'out'", id, "");
4792         if (! intermediate.setVertices(publicType.shaderQualifiers.vertices))
4793             error(loc, "cannot change previously set layout value", id, "");
4794         
4795         if (language == EShLangTessControl)
4796             checkIoArraysConsistency(loc);
4797     }
4798     if (publicType.shaderQualifiers.invocations) {
4799         if (publicType.qualifier.storage != EvqVaryingIn)
4800             error(loc, "can only apply to 'in'", "invocations", "");
4801         if (! intermediate.setInvocations(publicType.shaderQualifiers.invocations))
4802             error(loc, "cannot change previously set layout value", "invocations", "");
4803     }
4804     if (publicType.shaderQualifiers.geometry != ElgNone) {
4805         if (publicType.qualifier.storage == EvqVaryingIn) {
4806             switch (publicType.shaderQualifiers.geometry) {
4807             case ElgPoints:
4808             case ElgLines:
4809             case ElgLinesAdjacency:
4810             case ElgTriangles:
4811             case ElgTrianglesAdjacency:
4812             case ElgQuads:
4813             case ElgIsolines:
4814                 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
4815                     if (language == EShLangGeometry)
4816                         checkIoArraysConsistency(loc);
4817                 } else
4818                     error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
4819                 break;
4820             default:
4821                 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
4822             }
4823         } else if (publicType.qualifier.storage == EvqVaryingOut) {
4824             switch (publicType.shaderQualifiers.geometry) {
4825             case ElgPoints:
4826             case ElgLineStrip:
4827             case ElgTriangleStrip:
4828                 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
4829                     error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
4830                 break;
4831             default:
4832                 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
4833             }
4834         } else
4835             error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
4836     }
4837     if (publicType.shaderQualifiers.spacing != EvsNone) {
4838         if (publicType.qualifier.storage == EvqVaryingIn) {
4839             if (! intermediate.setVertexSpacing(publicType.shaderQualifiers.spacing))
4840                 error(loc, "cannot change previously set vertex spacing", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
4841         } else
4842             error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
4843     }
4844     if (publicType.shaderQualifiers.order != EvoNone) {
4845         if (publicType.qualifier.storage == EvqVaryingIn) {
4846             if (! intermediate.setVertexOrder(publicType.shaderQualifiers.order))
4847                 error(loc, "cannot change previously set vertex order", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
4848         } else
4849             error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
4850     }
4851     if (publicType.shaderQualifiers.pointMode) {
4852         if (publicType.qualifier.storage == EvqVaryingIn)
4853             intermediate.setPointMode();
4854         else
4855             error(loc, "can only apply to 'in'", "point_mode", "");
4856     }
4857     for (int i = 0; i < 3; ++i) {
4858         if (publicType.shaderQualifiers.localSize[i] > 1) {
4859             if (publicType.qualifier.storage == EvqVaryingIn) {
4860                 if (! intermediate.setLocalSize(i, publicType.shaderQualifiers.localSize[i]))
4861                     error(loc, "cannot change previously set size", "local_size", "");
4862                 else {
4863                     int max;
4864                     switch (i) {
4865                     case 0: max = resources.maxComputeWorkGroupSizeX; break;
4866                     case 1: max = resources.maxComputeWorkGroupSizeY; break;
4867                     case 2: max = resources.maxComputeWorkGroupSizeZ; break;
4868                     default: break;
4869                     }
4870                     if (intermediate.getLocalSize(i) > (unsigned int)max)
4871                         error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
4872
4873                     // Fix the existing constant gl_WorkGroupSize with this new information.
4874                     bool builtIn;
4875                     TSymbol* symbol = symbolTable.find("gl_WorkGroupSize", &builtIn);
4876                     if (builtIn)
4877                         makeEditable(symbol);
4878                     TVariable* workGroupSize = symbol->getAsVariable();
4879                     workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
4880                 }
4881             } else
4882                 error(loc, "can only apply to 'in'", "local_size", "");
4883         }
4884     }
4885     if (publicType.shaderQualifiers.earlyFragmentTests) {
4886         if (publicType.qualifier.storage == EvqVaryingIn)
4887             intermediate.setEarlyFragmentTests();
4888         else
4889             error(loc, "can only apply to 'in'", "early_fragment_tests", "");
4890     }
4891
4892     const TQualifier& qualifier = publicType.qualifier;
4893
4894     if (qualifier.isAuxiliary() ||
4895         qualifier.isMemory() ||
4896         qualifier.isInterpolation() ||
4897         qualifier.precision != EpqNone)
4898         error(loc, "cannot use auxiliary, memory, interpolation, or precision qualifier in a default qualifier declaration (declaration with no type)", "qualifier", "");
4899     // "The offset qualifier can only be used on block members of blocks..."
4900     // "The align qualifier can only be used on blocks or block members..."
4901     if (qualifier.hasOffset() ||
4902         qualifier.hasAlign())
4903         error(loc, "cannot use offset or align qualifiers in a default qualifier declaration (declaration with no type)", "layout qualifier", "");
4904
4905     layoutQualifierCheck(loc, qualifier);
4906
4907     switch (qualifier.storage) {
4908     case EvqUniform:
4909         if (qualifier.hasMatrix())
4910             globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
4911         if (qualifier.hasPacking())
4912             globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
4913         break;
4914     case EvqBuffer:
4915         if (qualifier.hasMatrix())
4916             globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
4917         if (qualifier.hasPacking())
4918             globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
4919         break;
4920     case EvqVaryingIn:
4921         break;
4922     case EvqVaryingOut:
4923         if (qualifier.hasStream())
4924             globalOutputDefaults.layoutStream = qualifier.layoutStream;
4925         if (qualifier.hasXfbBuffer())
4926             globalOutputDefaults.layoutXfbBuffer = qualifier.layoutXfbBuffer;
4927         if (globalOutputDefaults.hasXfbBuffer() && qualifier.hasXfbStride()) {
4928             if (! intermediate.setXfbBufferStride(globalOutputDefaults.layoutXfbBuffer, qualifier.layoutXfbStride))
4929                 error(loc, "all stride settings must match for xfb buffer", "xfb_stride", "%d", qualifier.layoutXfbBuffer);
4930         }
4931         break;
4932     default:
4933         error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
4934         return;
4935     }
4936
4937     if (qualifier.hasBinding())
4938         error(loc, "cannot declare a default, include a type or full declaration", "binding", "");
4939     if (qualifier.hasAnyLocation())
4940         error(loc, "cannot declare a default, use a full declaration", "location/component/index", "");
4941     if (qualifier.hasXfbOffset())
4942         error(loc, "cannot declare a default, use a full declaration", "xfb_offset", "");
4943 }
4944
4945 //
4946 // Take the sequence of statements that has been built up since the last case/default,
4947 // put it on the list of top-level nodes for the current (inner-most) switch statement,
4948 // and follow that by the case/default we are on now.  (See switch topology comment on
4949 // TIntermSwitch.)
4950 //
4951 void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
4952 {
4953     TIntermSequence* switchSequence = switchSequenceStack.back();
4954
4955     if (statements) {
4956         if (switchSequence->size() == 0)
4957             error(statements->getLoc(), "cannot have statements before first case/default label", "switch", "");
4958         statements->setOperator(EOpSequence);
4959         switchSequence->push_back(statements);
4960     }
4961     if (branchNode) {
4962         // check all previous cases for the same label (or both are 'default')
4963         for (unsigned int s = 0; s < switchSequence->size(); ++s) {
4964             TIntermBranch* prevBranch = (*switchSequence)[s]->getAsBranchNode();
4965             if (prevBranch) {
4966                 TIntermTyped* prevExpression = prevBranch->getExpression();
4967                 TIntermTyped* newExpression = branchNode->getAsBranchNode()->getExpression();
4968                 if (prevExpression == 0 && newExpression == 0)
4969                     error(branchNode->getLoc(), "duplicate label", "default", "");
4970                 else if (prevExpression != 0 &&
4971                           newExpression != 0 &&
4972                          prevExpression->getAsConstantUnion() &&
4973                           newExpression->getAsConstantUnion() &&
4974                          prevExpression->getAsConstantUnion()->getConstArray()[0].getIConst() ==
4975                           newExpression->getAsConstantUnion()->getConstArray()[0].getIConst())
4976                     error(branchNode->getLoc(), "duplicated value", "case", "");
4977             }
4978         }
4979         switchSequence->push_back(branchNode);
4980     }
4981 }
4982
4983 //
4984 // Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
4985 // into a switch node.
4986 //
4987 TIntermNode* TParseContext::addSwitch(TSourceLoc loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
4988 {
4989     profileRequires(loc, EEsProfile, 300, 0, "switch statements");
4990     profileRequires(loc, ENoProfile, 130, 0, "switch statements");
4991
4992     wrapupSwitchSubsequence(lastStatements, 0);
4993
4994     if (expression == 0 ||
4995         (expression->getBasicType() != EbtInt && expression->getBasicType() != EbtUint) ||
4996         expression->getType().isArray() || expression->getType().isMatrix() || expression->getType().isVector())
4997             error(loc, "condition must be a scalar integer expression", "switch", "");
4998
4999     // If there is nothing to do, drop the switch but still execute the expression
5000     TIntermSequence* switchSequence = switchSequenceStack.back();
5001     if (switchSequence->size() == 0)
5002         return expression;
5003
5004     if (lastStatements == 0) {
5005         warn(loc, "last case/default label not be followed by statements", "switch", "");
5006
5007         return expression;
5008     }
5009
5010     TIntermAggregate* body = new TIntermAggregate(EOpSequence);
5011     body->getSequence() = *switchSequenceStack.back();
5012     body->setLoc(loc);
5013
5014     TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
5015     switchNode->setLoc(loc);
5016
5017     return switchNode;
5018 }
5019
5020 } // end namespace glslang