2 //Copyright (C) 2002-2005 3Dlabs Inc. Ltd.
3 //Copyright (C) 2012-2013 LunarG, Inc.
7 //Redistribution and use in source and binary forms, with or without
8 //modification, are permitted provided that the following conditions
11 // Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
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.
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.
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.
37 #include "ParseHelper.h"
40 #include "osinclude.h"
44 #include "preprocessor/PpContext.h"
46 extern int yyparse(glslang::TParseContext*);
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)
59 // ensure we always have a linkage node, even if empty, to simplify tree topology algorithms
60 linkage = new TIntermAggregate;
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;
67 for (int type = 0; type < maxSamplerIndex; ++type)
68 defaultSamplerPrecision[type] = EpqNone;
70 // replace with real defaults for those that have them
71 if (profile == EEsProfile) {
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;
83 defaultPrecision[EbtInt] = EpqMedium;
84 defaultPrecision[EbtUint] = EpqMedium;
87 defaultPrecision[EbtInt] = EpqHigh;
88 defaultPrecision[EbtUint] = EpqHigh;
89 defaultPrecision[EbtFloat] = EpqHigh;
93 defaultPrecision[EbtSampler] = EpqLow;
94 defaultPrecision[EbtAtomicUint] = EpqHigh;
97 globalUniformDefaults.clear();
98 globalUniformDefaults.layoutMatrix = ElmColumnMajor;
99 globalUniformDefaults.layoutPacking = ElpShared;
101 globalBufferDefaults.clear();
102 globalBufferDefaults.layoutMatrix = ElmColumnMajor;
103 globalBufferDefaults.layoutPacking = ElpShared;
105 globalInputDefaults.clear();
106 globalOutputDefaults.clear();
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;
117 if (language == EShLangGeometry)
118 globalOutputDefaults.layoutStream = 0;
121 TParseContext::~TParseContext()
123 delete [] atomicUintOffsets;
126 void TParseContext::setLimits(const TBuiltInResource& r)
130 anyIndexLimits = ! limits.generalAttributeMatrixVectorIndexing ||
131 ! limits.generalConstantMatrixVectorIndexing ||
132 ! limits.generalSamplerIndexing ||
133 ! limits.generalUniformIndexing ||
134 ! limits.generalVariableIndexing ||
135 ! limits.generalVaryingIndexing;
137 intermediate.setLimits(resources);
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;
148 // Parse an array of strings using yyparse, going through the
149 // preprocessor to tokenize the shader strings, then through
152 // Returns true for successful acceptance of the shader, false if any errors.
154 bool TParseContext::parseShaderStrings(TPpContext& ppContext, TInputScanner& input, bool versionWillBeError)
156 currentScanner = &input;
157 ppContext.setInput(input, versionWillBeError);
161 return numErrors == 0;
164 // This is called from bison when it has a parse (syntax) error
165 void TParseContext::parserError(const char* s)
168 if (tokensBeforeEOF == 1)
169 error(getCurrentLoc(), "", "pre-mature EOF", s, "");
171 error(getCurrentLoc(), "", "", s, "");
174 void TParseContext::handlePragma(TSourceLoc loc, const TVector<TString>& tokens)
176 if (tokens.size() == 0)
179 if (tokens[0].compare("optimize") == 0) {
180 if (tokens.size() != 4) {
181 error(loc, "optimize pragma syntax is incorrect", "#pragma", "");
185 if (tokens[1].compare("(") != 0) {
186 error(loc, "\"(\" expected after 'optimize' keyword", "#pragma", "");
190 if (tokens[2].compare("on") == 0)
191 contextPragma.optimize = true;
192 else if (tokens[2].compare("off") == 0)
193 contextPragma.optimize = false;
195 error(loc, "\"on\" or \"off\" expected after '(' for 'optimize' pragma", "#pragma", "");
199 if (tokens[3].compare(")") != 0) {
200 error(loc, "\")\" expected to end 'optimize' pragma", "#pragma", "");
203 } else if (tokens[0].compare("debug") == 0) {
204 if (tokens.size() != 4) {
205 error(loc, "debug pragma syntax is incorrect", "#pragma", "");
209 if (tokens[1].compare("(") != 0) {
210 error(loc, "\"(\" expected after 'debug' keyword", "#pragma", "");
214 if (tokens[2].compare("on") == 0)
215 contextPragma.debug = true;
216 else if (tokens[2].compare("off") == 0)
217 contextPragma.debug = false;
219 error(loc, "\"on\" or \"off\" expected after '(' for 'debug' pragma", "#pragma", "");
223 if (tokens[3].compare(")") != 0) {
224 error(loc, "\")\" expected to end 'debug' pragma", "#pragma", "");
230 ///////////////////////////////////////////////////////////////////////
232 // Sub- vector and matrix fields
234 ////////////////////////////////////////////////////////////////////////
237 // Look at a '.' field selector string and change it into offsets
238 // for a vector or scalar
240 // Returns true if there is no error.
242 bool TParseContext::parseVectorFields(TSourceLoc loc, const TString& compString, int vecSize, TVectorFields& fields)
244 fields.num = (int) compString.size();
245 if (fields.num > 4) {
246 error(loc, "illegal vector field selection", compString.c_str(), "");
256 for (int i = 0; i < fields.num; ++i) {
257 switch (compString[i]) {
259 fields.offsets[i] = 0;
263 fields.offsets[i] = 0;
267 fields.offsets[i] = 0;
271 fields.offsets[i] = 1;
275 fields.offsets[i] = 1;
279 fields.offsets[i] = 1;
283 fields.offsets[i] = 2;
287 fields.offsets[i] = 2;
291 fields.offsets[i] = 2;
296 fields.offsets[i] = 3;
300 fields.offsets[i] = 3;
304 fields.offsets[i] = 3;
308 error(loc, "illegal vector field selection", compString.c_str(), "");
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(), "");
320 if (fieldSet[i] != fieldSet[i-1]) {
321 error(loc, "illegal - vector component fields not from the same set", compString.c_str(), "");
330 ///////////////////////////////////////////////////////////////////////
334 ////////////////////////////////////////////////////////////////////////
337 // Used to output syntax, parsing, and semantic errors.
339 void C_DECL TParseContext::error(TSourceLoc loc, const char* szReason, const char* szToken,
340 const char* szExtraInfoFormat, ...)
342 const int maxSize = GlslangMaxTokenLength + 200;
343 char szExtraInfo[maxSize];
346 va_start(marker, szExtraInfoFormat);
348 safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, marker);
350 infoSink.info.prefix(EPrefixError);
351 infoSink.info.location(loc);
352 infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n";
359 void C_DECL TParseContext::warn(TSourceLoc loc, const char* szReason, const char* szToken,
360 const char* szExtraInfoFormat, ...)
362 if (messages & EShMsgSuppressWarnings)
365 const int maxSize = GlslangMaxTokenLength + 200;
366 char szExtraInfo[maxSize];
369 va_start(marker, szExtraInfoFormat);
371 safe_vsprintf(szExtraInfo, maxSize, szExtraInfoFormat, marker);
373 infoSink.info.prefix(EPrefixWarning);
374 infoSink.info.location(loc);
375 infoSink.info << "'" << szToken << "' : " << szReason << " " << szExtraInfo << "\n";
381 // Handle seeing a variable identifier in the grammar.
383 TIntermTyped* TParseContext::handleVariable(TSourceLoc loc, TSymbol* symbol, TString* string)
385 TIntermTyped* node = 0;
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());
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.
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);
404 const TVariable* variable;
405 const TAnonMember* anon = symbol ? symbol->getAsAnonMember() : 0;
407 // It was a member of an anonymous container.
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);
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(), "");
419 // Not a member of an anonymous container.
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(), "");
427 // Recovery, if it wasn't found or was not a variable.
429 variable = new TVariable(string, TType(EbtVoid));
431 if (variable->getType().getQualifier().storage == EvqConst)
432 node = intermediate.addConstantUnion(variable->getConstArray(), variable->getType(), loc);
434 node = intermediate.addSymbol(*variable, loc);
437 if (variable->getType().getQualifier().isIo())
438 intermediate.addIoAccessed(*string);
444 // Handle seeing a base[index] dereference in the grammar.
446 TIntermTyped* TParseContext::handleBracketDereference(TSourceLoc loc, TIntermTyped* base, TIntermTyped* index)
448 TIntermTyped* result = 0;
451 if (index->getQualifier().storage == EvqConst) {
452 indexValue = index->getAsConstantUnion()->getConstArray()[0].getIConst();
453 checkIndex(loc, base->getType(), indexValue);
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(), "");
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);
465 // at least one of base and index is variable...
467 if (base->getAsSymbolNode() && isIoResizeArray(base->getType()))
468 handleIoResizeArrayAccess(loc, base);
470 if (index->getQualifier().storage == EvqConst) {
471 if (base->getType().isImplicitlySizedArray())
472 updateImplicitArraySize(loc, base, indexValue);
473 result = intermediate.addIndex(EOpIndexDirect, base, index, loc);
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");
479 error(loc, "", "[", "array must be redeclared with a size before being indexed with a variable");
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);
491 result = intermediate.addIndex(EOpIndexIndirect, base, index, loc);
496 // Insert dummy error-recovery result
497 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
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;
504 newType.getQualifier().storage = EvqTemporary;
505 result->setType(newType);
508 handleIndexLimits(loc, base, index);
514 void TParseContext::checkIndex(TSourceLoc loc, const TType& type, int& index)
517 error(loc, "", "[", "index out of range '%d'", index);
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;
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;
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;
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)
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);
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)
560 // copyUp() does a deep copy of the type.
561 symbol = symbolTable.copyUp(symbol);
563 // Also, see if it's tied to IO resizing
564 if (isIoResizeArray(symbol->getType()))
565 ioArraySymbolResizeList.push_back(symbol);
567 // Also, save it in the AST for linker use.
568 intermediate.addSymbolLinkageNode(linkage, *symbol);
571 // Return true if this is a geometry shader input array or tessellation control output array.
572 bool TParseContext::isIoResizeArray(const TType& type) const
574 return type.isArray() &&
575 ((language == EShLangGeometry && type.getQualifier().storage == EvqVaryingIn) ||
576 (language == EShLangTessControl && type.getQualifier().storage == EvqVaryingOut && ! type.getQualifier().patch));
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)
582 if (! type.isArray() || type.getQualifier().patch || symbolTable.atBuiltInLevel())
585 assert(! isIoResizeArray(type));
587 if (type.getQualifier().storage != EvqVaryingIn || type.getQualifier().patch)
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);
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)
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());
610 // Handle a dereference of a geometry shader input array or tessellation control output array.
611 // See ioArraySymbolResizeList comment in ParseHelper.h.
613 void TParseContext::handleIoResizeArrayAccess(TSourceLoc loc, TIntermTyped* base)
615 TIntermSymbol* symbolNode = base->getAsSymbolNode();
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();
624 symbolNode->getWritableType().changeArraySize(newSize);
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
633 // Types without an array size will be given one.
634 // Types already having a size that is wrong will get an error.
636 void TParseContext::checkIoArraysConsistency(TSourceLoc loc, bool tailOnly)
638 int requiredSize = getIoArrayImplicitSize();
639 if (requiredSize == 0)
643 if (language == EShLangGeometry)
644 feature = TQualifier::getGeometryString(intermediate.getInputPrimitive());
645 else if (language == EShLangTessControl)
646 feature = "vertices";
649 checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList.back()->getWritableType(), ioArraySymbolResizeList.back()->getName());
653 for (size_t i = 0; i < ioArraySymbolResizeList.size(); ++i)
654 checkIoArrayConsistency(loc, requiredSize, feature, ioArraySymbolResizeList[i]->getWritableType(), ioArraySymbolResizeList[i]->getName());
657 int TParseContext::getIoArrayImplicitSize() const
659 if (language == EShLangGeometry)
660 return TQualifier::mapGeometryToSize(intermediate.getInputPrimitive());
661 else if (language == EShLangTessControl)
662 return intermediate.getVertices();
667 void TParseContext::checkIoArrayConsistency(TSourceLoc loc, int requiredSize, const char* feature, TType& type, const TString& name)
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());
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)
684 rValueErrorCheck(loc, str, left->getAsTyped());
685 rValueErrorCheck(loc, str, right->getAsTyped());
687 TIntermTyped* result = intermediate.addBinaryMath(op, left, right, loc);
689 binaryOpError(loc, str, left->getCompleteString(), right->getCompleteString());
694 // Handle seeing a unary node with a math operation.
695 TIntermTyped* TParseContext::handleUnaryMath(TSourceLoc loc, const char* str, TOperator op, TIntermTyped* childNode)
697 rValueErrorCheck(loc, str, childNode);
699 TIntermTyped* result = intermediate.addUnaryMath(op, childNode, loc);
704 unaryOpError(loc, str, childNode->getCompleteString());
710 // Handle seeing a base.field dereference in the grammar.
712 TIntermTyped* TParseContext::handleDotDereference(TSourceLoc loc, TIntermTyped* base, TString& field)
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().
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);
730 error(loc, "does not operate on this type:", field.c_str(), base->getType().getCompleteString().c_str());
735 return intermediate.addMethod(base, TType(EbtInt), &field, loc);
738 // It's not .length() if we get to here.
740 if (base->isArray()) {
741 error(loc, "cannot apply to an array:", ".", field.c_str());
746 // It's neither an array nor .length() if we get here,
747 // leaving swizzles and struct/block dereferences.
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);
757 TVectorFields fields;
758 if (! parseVectorFields(loc, field, base->getVectorSize(), fields)) {
760 fields.offsets[0] = 0;
763 if (base->isScalar()) {
767 TType type(base->getBasicType(), EvqTemporary, fields.num);
768 return addConstructor(loc, base, type, mapTypeToConstructorOp(type));
772 if (base->getType().getQualifier().storage == EvqConst)
773 result = intermediate.foldSwizzle(base, fields, loc);
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));
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()));
786 } else if (base->getBasicType() == EbtStruct || base->getBasicType() == EbtBlock) {
787 const TTypeList* fields = base->getType().getStruct();
788 bool fieldFound = false;
790 for (member = 0; member < (int)fields->size(); ++member) {
791 if ((*fields)[member].type->getFieldName() == field) {
797 if (base->getType().getQualifier().storage == EvqConst)
798 result = intermediate.foldDereference(base, member, loc);
800 TIntermTyped* index = intermediate.addConstantUnion(member, loc);
801 result = intermediate.addIndex(EOpIndexDirectStruct, base, index, loc);
802 result->setType(*(*fields)[member].type);
805 error(loc, "no such field in structure", field.c_str(), "");
807 error(loc, "does not apply to this type:", field.c_str(), base->getType().getCompleteString().c_str());
813 // Handle seeing a function declarator in the grammar. This is the precursor
814 // to recognizing a function prototype or function definition.
816 TFunction* TParseContext::handleFunctionDeclarator(TSourceLoc loc, TFunction& function, bool prototype)
818 // ES can't declare prototypes inside functions
819 if (! symbolTable.atGlobalLevel())
820 requireProfile(loc, ~EEsProfile, "local function declaration");
823 // Multiple declarations of the same function name are allowed.
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).
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
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.
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;
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);
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);
853 arrayObjectCheck(loc, function.getType(), "array in function return type");
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();
861 if (prevDec && ! builtIn)
862 symbol->getAsFunction()->setPrototyped(); // need a writable one, but like having prevDec as a const
863 function.setPrototyped();
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(), "");
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.
881 // Handle seeing the function prototype in front of a function definition in the grammar.
882 // The body is handled after this function returns.
884 TIntermAggregate* TParseContext::handleFunctionDefinition(TSourceLoc loc, TFunction& function)
886 currentCaller = function.getMangledName();
887 TSymbol* symbol = symbolTable.find(function.getMangledName());
888 TFunction* prevDec = symbol ? symbol->getAsFunction() : 0;
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.
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(), "");
900 if (prevDec && ! prevDec->isDefined()) {
901 prevDec->setDefined();
903 // Remember the return type for later checking for RETURN statements.
904 currentFunctionType = &(prevDec->getType());
906 currentFunctionType = new TType(EbtVoid);
907 functionReturnsValue = false;
910 // Raise error message if main function takes any parameters or returns anything other than void
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();
921 // New symbol table scope for body of function plus its arguments
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).
930 // Also, accumulate the list of parameters into the HIL, so lower level code
931 // knows where to find parameters.
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);
939 // Insert the parameters with name in the symbol table.
940 if (! symbolTable.insert(*variable))
941 error(loc, "redefinition", variable->getName().c_str(), "");
943 // Transfer ownership of name pointer to symbol table.
946 // Add the parameter to the HIL
947 paramNodes = intermediate.growAggregate(paramNodes,
948 intermediate.addSymbol(*variable, loc),
952 paramNodes = intermediate.growAggregate(paramNodes, intermediate.addSymbol(0, "", *param.type, loc), loc);
954 intermediate.setAggregateOperator(paramNodes, EOpParameters, TType(EbtVoid), loc);
955 loopNestingLevel = 0;
956 controlFlowNestingLevel = 0;
962 // Handle seeing function call syntax in the grammar, which could be any of
963 // - .length() method
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)
968 // - subroutine call (not implemented yet)
970 TIntermTyped* TParseContext::handleFunctionCall(TSourceLoc loc, TFunction* function, TIntermNode* arguments)
972 TIntermTyped* result = 0;
974 TOperator op = function->getBuiltInOp();
975 if (op == EOpArrayLength)
976 result = handleLengthMethod(loc, function, arguments);
977 else if (op != EOpNull) {
979 // Then this should be a constructor.
980 // Don't go through the symbol table for constructors.
981 // Their parameters will be verified algorithmically.
983 TType type(EbtVoid); // use this to get the type back
984 if (! constructorError(loc, arguments, *function, op, type)) {
986 // It's a constructor, of type 'type'.
988 result = addConstructor(loc, arguments, type, op);
990 error(loc, "cannot construct with these arguments", type.getCompleteString().c_str(), "");
994 // Find it in the symbol table.
996 const TFunction* fnCandidate;
998 fnCandidate = findFunction(loc, *function, builtIn);
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.
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());
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", "");
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", "");
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
1043 // Convert 'in' arguments
1044 addInputArgumentConversions(*fnCandidate, arguments); // arguments may be modified if it's just a single argument node
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());
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());
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());
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
1066 call->setUserDefined();
1067 intermediate.addToCallGraph(infoSink, currentCaller, fnCandidate->getMangledName());
1071 nonOpBuiltInCheck(loc, *fnCandidate, *call);
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);
1083 result = addOutputArgumentConversions(*fnCandidate, *result->getAsAggregate());
1088 // generic error recovery
1089 // TODO: simplification: localize all the error recoveries that look like this, and taking type into account to reduce cascades
1091 result = intermediate.addConstantUnion(0.0, EbtFloat, loc);
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.
1100 // Return resulting tree node.
1101 TIntermTyped* TParseContext::handleLengthMethod(TSourceLoc loc, TFunction* function, TIntermNode* intermNode)
1105 if (function->getParamCount() > 0)
1106 error(loc, "method does not accept any arguments", function->getName().c_str(), "");
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();
1124 if (intermNode->getAsSymbolNode() && isIoResizeArray(type))
1125 error(loc, "", function->getName().c_str(), "array must first be sized by a redeclaration or layout qualifier");
1127 error(loc, "", function->getName().c_str(), "array must be declared with a size before using this method");
1130 length = type.getArraySize();
1131 } else if (type.isMatrix())
1132 length = type.getMatrixCols();
1133 else if (type.isVector())
1134 length = type.getVectorSize();
1136 // we should not get here, because earlier semantic checking should have prevented this path
1137 error(loc, ".length()", "unexpected use of .length()", "");
1144 return intermediate.addConstantUnion(length, loc);
1148 // Add any needed implicit conversions for function-call arguments to input parameters.
1150 void TParseContext::addInputArgumentConversions(const TFunction& function, TIntermNode*& arguments) const
1152 TIntermAggregate* aggregate = arguments->getAsAggregate();
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);
1167 aggregate->getSequence()[i] = arg;
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.
1181 // Returns a node of a subtree that evaluates to the return value of the function.
1183 TIntermTyped* TParseContext::addOutputArgumentConversions(const TFunction& function, TIntermAggregate& intermNode) const
1185 TIntermSequence& arguments = intermNode.getSequence();
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;
1196 if (! outputConversions)
1199 // Setup for the new tree, if needed:
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());
1215 conversionTree = &intermNode;
1217 conversionTree = intermediate.makeAggregate(conversionTree);
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());
1236 // Finalize the tree topology (see bigger comment above).
1238 // do the "..., tempRet" bit from above
1239 TIntermSymbol* tempRetNode = intermediate.addSymbol(*tempRet, intermNode.getLoc());
1240 conversionTree = intermediate.growAggregate(conversionTree, tempRetNode, intermNode.getLoc());
1242 conversionTree = intermediate.setAggregateOperator(conversionTree, EOpComma, intermNode.getType(), intermNode.getLoc());
1244 return conversionTree;
1248 // Do additional checking of built-in function calls that were not mapped
1249 // to built-in operations (e.g., texturing functions).
1251 // Assumes there has been a semantically correct match to a built-in function.
1253 void TParseContext::nonOpBuiltInCheck(TSourceLoc loc, const TFunction& fnCandidate, TIntermAggregate& callNode)
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;
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);
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);
1272 profileRequires(loc, ~EEsProfile, 400, GL_ARB_gpu_shader5, feature);
1273 if (! fnCandidate[0].type->getSampler().shadow)
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)
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)
1291 profileRequires(loc, ~EEsProfile, 400, GL_ARB_texture_gather, feature);
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");
1300 error(loc, "must be a compile-time constant:", feature, "component argument");
1303 // this is only for functions not starting "textureGather"...
1304 if (fnCandidate.getName().find("Offset") != TString::npos) {
1306 // Handle texture-offset limits checking
1308 if (fnCandidate.getName().compare("textureOffset") == 0)
1310 else if (fnCandidate.getName().compare("texelFetchOffset") == 0)
1312 else if (fnCandidate.getName().compare("textureProjOffset") == 0)
1314 else if (fnCandidate.getName().compare("textureLodOffset") == 0)
1316 else if (fnCandidate.getName().compare("textureProjLodOffset") == 0)
1318 else if (fnCandidate.getName().compare("textureGradOffset") == 0)
1320 else if (fnCandidate.getName().compare("textureProjGradOffset") == 0)
1324 if (! callNode.getSequence()[arg]->getAsConstantUnion())
1325 error(loc, "argument must be compile-time constant", "texel offset", "");
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]");
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");
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(), "");
1354 // Handle seeing a built-in constructor in a grammar production.
1356 TFunction* TParseContext::handleConstructorCall(TSourceLoc loc, const TPublicType& publicType)
1358 TType type(publicType);
1359 type.getQualifier().precision = EpqNone;
1361 if (type.isArray()) {
1362 profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "arrayed constructor");
1363 profileRequires(loc, EEsProfile, 300, 0, "arrayed constructor");
1366 TOperator op = mapTypeToConstructorOp(type);
1368 if (op == EOpNull) {
1369 error(loc, "cannot construct this type", type.getBasicString(), "");
1370 op = EOpConstructFloat;
1371 TType errorType(EbtFloat);
1372 type.shallowCopy(errorType);
1377 return new TFunction(&empty, type, op);
1381 // Given a type, find what operation would fully construct it.
1383 TOperator TParseContext::mapTypeToConstructorOp(const TType& type) const
1385 if (type.isStruct())
1386 return EOpConstructStruct;
1389 switch (type.getBasicType()) {
1391 if (type.isMatrix()) {
1392 switch (type.getMatrixCols()) {
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
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
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
1417 default: break; // some compilers want this
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
1430 if (type.getMatrixCols()) {
1431 switch (type.getMatrixCols()) {
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
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
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
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
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
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
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
1503 // Same error message for all places assignments don't work.
1505 void TParseContext::assignError(TSourceLoc loc, const char* op, TString left, TString right)
1507 error(loc, "", op, "cannot convert from '%s' to '%s'",
1508 right.c_str(), left.c_str());
1512 // Same error message for all places unary operations don't work.
1514 void TParseContext::unaryOpError(TSourceLoc loc, const char* op, TString operand)
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());
1522 // Same error message for all binary operations don't work.
1524 void TParseContext::binaryOpError(TSourceLoc loc, const char* op, TString left, TString right)
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());
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.
1537 void TParseContext::variableCheck(TIntermTyped*& nodePtr)
1539 TIntermSymbol* symbol = nodePtr->getAsSymbolNode();
1543 if (symbol->getType().getBasicType() == EbtVoid) {
1544 error(symbol->getLoc(), "undeclared identifier", symbol->getName().c_str(), "");
1546 // Add to symbol table to prevent future error messages on the same name
1548 TVariable* fakeVariable = new TVariable(&symbol->getName(), TType(EbtFloat));
1549 symbolTable.insert(*fakeVariable);
1551 // substitute a symbol node for this new variable
1552 nodePtr = intermediate.addSymbol(*fakeVariable, symbol->getLoc());
1554 switch (symbol->getQualifier().storage) {
1556 profileRequires(symbol->getLoc(), ENoProfile, 120, 0, "gl_PointCoord");
1558 default: break; // some compilers want this
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.
1567 // Returns true if the was an error.
1569 bool TParseContext::lValueErrorCheck(TSourceLoc loc, const char* op, TIntermTyped* node)
1571 TIntermBinary* binaryNode = node->getAsBinaryNode();
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());
1584 int offset[4] = {0,0,0,0};
1586 TIntermTyped* rightNode = binaryNode->getRight();
1587 TIntermAggregate *aggrNode = rightNode->getAsAggregate();
1589 for (TIntermSequence::iterator p = aggrNode->getSequence().begin();
1590 p != aggrNode->getSequence().end(); p++) {
1591 int value = (*p)->getAsTyped()->getAsConstantUnion()->getConstArray()[0].getIConst();
1593 if (offset[value] > 1) {
1594 error(loc, " l-value of swizzle cannot have duplicate components", op, "", "");
1605 error(loc, " l-value required", op, "", "");
1611 const char* symbol = 0;
1612 TIntermSymbol* symNode = node->getAsSymbolNode();
1614 symbol = symNode->getName().c_str();
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;
1628 if (node->getQualifier().readonly)
1629 message = "can't modify a readonly buffer";
1634 // Type that can't be written to?
1636 switch (node->getBasicType()) {
1638 message = "can't modify a sampler";
1641 message = "can't modify an atomic_uint";
1644 message = "can't modify void";
1651 if (message == 0 && binaryNode == 0 && symNode == 0) {
1652 error(loc, " l-value required", op, "", "");
1659 // Everything else is okay, no error.
1665 // If we get here, we have an error and a message.
1668 error(loc, " l-value required", op, "\"%s\" (%s)", symbol, message);
1670 error(loc, " l-value required", op, "(%s)", message);
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)
1681 TIntermBinary* binaryNode = node->getAsBinaryNode();
1683 switch(binaryNode->getOp()) {
1684 case EOpIndexDirect:
1685 case EOpIndexIndirect:
1686 case EOpIndexDirectStruct:
1687 case EOpVectorSwizzle:
1688 rValueErrorCheck(loc, op, binaryNode->getLeft());
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());
1702 // Both test, and if necessary spit out an error, to see if the node is really
1705 void TParseContext::constantValueCheck(TIntermTyped* node, const char* token)
1707 if (node->getQualifier().storage != EvqConst)
1708 error(node->getLoc(), "constant expression required", token, "");
1712 // Both test, and if necessary spit out an error, to see if the node is really
1715 void TParseContext::integerCheck(const TIntermTyped* node, const char* token)
1717 if ((node->getBasicType() == EbtInt || node->getBasicType() == EbtUint) && node->isScalar())
1720 error(node->getLoc(), "scalar integer expression required", token, "");
1724 // Both test, and if necessary spit out an error, to see if we are currently
1727 void TParseContext::globalCheck(TSourceLoc loc, const char* token)
1729 if (! symbolTable.atGlobalLevel())
1730 error(loc, "not allowed in nested scope", token, "");
1734 // Reserved errors for GLSL.
1736 void TParseContext::reservedErrorCheck(TSourceLoc loc, const TString& identifier)
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(), "");
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(), "");
1753 // Reserved errors for the preprocessor.
1755 void TParseContext::reservedPpErrorCheck(TSourceLoc loc, const char* identifier, const char* op)
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);
1769 // See if this version/profile allows use of the line-continuation character '\'.
1771 // Returns true if a line continuation should be done.
1773 bool TParseContext::lineContinuationCheck(TSourceLoc loc, bool endOfComment)
1775 const char* message = "line continuation";
1777 bool lineContinuationAllowed = (profile == EEsProfile && version >= 300) ||
1778 (profile != EEsProfile && (version >= 420 || extensionsTurnedOn(1, &GL_ARB_shading_language_420pack)));
1781 if (lineContinuationAllowed)
1782 warn(loc, "used at end of comment; the following line is still part of the comment", message, "");
1784 warn(loc, "used at end of comment, but this version does not provide line continuation", message, "");
1786 return lineContinuationAllowed;
1789 if (messages & EShMsgRelaxedErrors) {
1790 if (! lineContinuationAllowed)
1791 warn(loc, "not allowed in this version", message, "");
1794 profileRequires(loc, EEsProfile, 300, 0, message);
1795 profileRequires(loc, ~EEsProfile, 420, GL_ARB_shading_language_420pack, message);
1798 return lineContinuationAllowed;
1801 bool TParseContext::builtInName(const TString& identifier)
1803 return identifier.compare(0, 3, "gl_") == 0;
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.
1811 // Returns true if there was an error in construction.
1813 bool TParseContext::constructorError(TSourceLoc loc, TIntermNode* node, TFunction& function, TOperator op, TType& type)
1815 type.shallowCopy(function.getType());
1817 bool constructingMatrix = false;
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;
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.
1850 bool constType = true;
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();
1858 if (constructingMatrix && function[i].type->isMatrix())
1859 matrixInMatrix = true;
1862 if (op != EOpConstructStruct && ! type.isArray() && size >= type.computeNumComponents())
1864 if (function[i].type->getQualifier().storage != EvqConst)
1866 if (function[i].type->isArray())
1871 type.getQualifier().storage = EvqConst;
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", "");
1883 if (arrayArg && op != EOpConstructStruct) {
1884 error(loc, "constructing from a non-dereferenced array", "constructor", "");
1888 if (matrixInMatrix && ! type.isArray()) {
1889 profileRequires(loc, ENoProfile, 120, 0, "constructing matrix from matrix");
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", "");
1899 error(loc, "too many arguments", "constructor", "");
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", "");
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", "");
1914 TIntermTyped* typed = node->getAsTyped();
1916 error(loc, "constructor argument does not have a type", "constructor", "");
1919 if (op != EOpConstructStruct && typed->getBasicType() == EbtSampler) {
1920 error(loc, "cannot convert a sampler", "constructor", "");
1923 if (op != EOpConstructStruct && typed->getBasicType() == EbtAtomicUint) {
1924 error(loc, "cannot convert an atomic_uint", "constructor", "");
1927 if (typed->getBasicType() == EbtVoid) {
1928 error(loc, "cannot convert a void", "constructor", "");
1935 // Checks to see if a void variable has been declared and raise an error message for such a case
1937 // returns true in case of an error
1939 bool TParseContext::voidErrorCheck(TSourceLoc loc, const TString& identifier, const TBasicType basicType)
1941 if (basicType == EbtVoid) {
1942 error(loc, "illegal use of type 'void'", identifier.c_str(), "");
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)
1952 if (type->getBasicType() != EbtBool || type->isArray() || type->isMatrix() || type->isVector())
1953 error(loc, "boolean expression expected", "", "");
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)
1959 if (pType.basicType != EbtBool || pType.arraySizes || pType.matrixCols > 1 || (pType.vectorSize > 1))
1960 error(loc, "boolean expression expected", "", "");
1963 void TParseContext::samplerCheck(TSourceLoc loc, const TType& type, const TString& identifier)
1965 if (type.getQualifier().storage == EvqUniform)
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());
1974 void TParseContext::atomicUintCheck(TSourceLoc loc, const TType& type, const TString& identifier)
1976 if (type.getQualifier().storage == EvqUniform)
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());
1986 // move from parameter/unknown qualifiers to pipeline in/out qualifiers
1988 void TParseContext::pipeInOutFix(TSourceLoc loc, TQualifier& qualifier)
1990 switch (qualifier.storage) {
1992 profileRequires(loc, ENoProfile, 130, 0, "in for stage inputs");
1993 profileRequires(loc, EEsProfile, 300, 0, "in for stage inputs");
1994 qualifier.storage = EvqVaryingIn;
1997 profileRequires(loc, ENoProfile, 130, 0, "out for stage outputs");
1998 profileRequires(loc, EEsProfile, 300, 0, "out for stage outputs");
1999 qualifier.storage = EvqVaryingOut;
2002 qualifier.storage = EvqVaryingIn;
2003 error(loc, "cannot use 'inout' at global scope", "", "");
2010 void TParseContext::globalQualifierCheck(TSourceLoc loc, const TQualifier& qualifier, const TPublicType& publicType)
2012 if (! symbolTable.atGlobalLevel())
2015 if (qualifier.isMemory() && ! publicType.isImage() && publicType.qualifier.storage != EvqBuffer)
2016 error(loc, "memory qualifiers cannot be used on this type", "", "");
2018 if (qualifier.storage == EvqBuffer && publicType.basicType != EbtBlock)
2019 error(loc, "buffers can be declared only as blocks", "buffer", "");
2021 if (qualifier.storage != EvqVaryingIn && qualifier.storage != EvqVaryingOut)
2024 // now, knowing it is a shader in/out, do all the in/out semantic checks
2026 if (publicType.basicType == EbtBool) {
2027 error(loc, "cannot be bool", GetStorageQualifierString(qualifier.storage), "");
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));
2041 if (qualifier.patch && qualifier.isInterpolation())
2042 error(loc, "cannot use interpolation qualifiers with patch", "patch", "");
2044 if (qualifier.storage == EvqVaryingIn) {
2047 if (publicType.basicType == EbtStruct) {
2048 error(loc, "cannot be a structure or array", GetStorageQualifierString(qualifier.storage), "");
2051 if (publicType.arraySizes) {
2052 requireProfile(loc, ~EEsProfile, "vertex input arrays");
2053 profileRequires(loc, ENoProfile, 150, 0, "vertex input arrays");
2055 if (qualifier.isAuxiliary() || qualifier.isInterpolation() || qualifier.isMemory() || qualifier.invariant)
2056 error(loc, "vertex input cannot be further qualified", "", "");
2059 case EShLangTessControl:
2060 if (qualifier.patch)
2061 error(loc, "can only use on output in tessellation-control shader", "patch", "");
2064 case EShLangTessEvaluation:
2067 case EShLangGeometry:
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");
2077 case EShLangCompute:
2078 if (! symbolTable.atBuiltInLevel())
2079 error(loc, "global storage input qualifier cannot be used in a compute shader", "in", "");
2086 // qualifier.storage == EvqVaryingOut
2089 if (publicType.userDef) {
2090 profileRequires(loc, EEsProfile, 300, 0, "vertex-shader struct output");
2091 profileRequires(loc, ~EEsProfile, 150, 0, "vertex-shader struct output");
2095 case EShLangTessControl:
2098 case EShLangTessEvaluation:
2099 if (qualifier.patch)
2100 error(loc, "can only use on input in tessellation-evaluation shader", "patch", "");
2103 case EShLangGeometry:
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), "");
2112 if (publicType.matrixRows > 0) {
2113 error(loc, "cannot be a matrix", GetStorageQualifierString(qualifier.storage), "");
2118 case EShLangCompute:
2119 error(loc, "global storage output qualifier cannot be used in a compute shader", "out", "");
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.
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.
2137 void TParseContext::mergeQualifiers(TSourceLoc loc, TQualifier& dst, const TQualifier& src, bool force)
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)", "", "");
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)", "", "");
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", "", "");
2161 // function parameters
2162 if (src.storage == EvqConst && (dst.storage == EvqIn || dst.storage == EvqOut))
2163 error(loc, "in/out must appear before const", "", "");
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), "");
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;
2184 // Layout qualifiers
2185 mergeObjectLayoutQualifiers(loc, dst, src, false);
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);
2204 error(loc, "replicated qualifiers", "", "");
2207 void TParseContext::setDefaultPrecision(TSourceLoc loc, TPublicType& publicType, TPrecisionQualifier qualifier)
2209 TBasicType basicType = publicType.basicType;
2211 if (basicType == EbtSampler) {
2212 defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)] = qualifier;
2214 return; // all is well
2217 if (basicType == EbtInt || basicType == EbtFloat) {
2218 if (publicType.isScalar()) {
2219 defaultPrecision[basicType] = qualifier;
2220 if (basicType == EbtInt)
2221 defaultPrecision[EbtUint] = qualifier;
2223 return; // all is well
2227 if (basicType == EbtAtomicUint) {
2228 if (qualifier != EpqHigh)
2229 error(loc, "can only apply highp to atomic_uint", "precision", "");
2234 error(loc, "cannot apply precision statement to this type; use 'float', 'int' or a sampler type", TType::getBasicString(basicType), "");
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)
2241 int arrayIndex = sampler.arrayed ? 1 : 0;
2242 int shadowIndex = sampler.shadow ? 1 : 0;
2243 int externalIndex = sampler.external ? 1 : 0;
2245 return EsdNumDims * (EbtNumTypes * (2 * (2 * arrayIndex + shadowIndex) + externalIndex) + sampler.type) + sampler.dim;
2248 TPrecisionQualifier TParseContext::getDefaultPrecision(TPublicType& publicType)
2250 if (publicType.basicType == EbtSampler)
2251 return defaultSamplerPrecision[computeSamplerTypeIndex(publicType.sampler)];
2253 return defaultPrecision[publicType.basicType];
2256 void TParseContext::precisionQualifierCheck(TSourceLoc loc, TPublicType& publicType)
2258 // Built-in symbols are allowed some ambiguous precisions, to be pinned down
2259 // later by context.
2260 if (profile != EEsProfile || parsingBuiltins)
2263 if (publicType.basicType == EbtAtomicUint && publicType.qualifier.precision != EpqNone && publicType.qualifier.precision != EpqHigh)
2264 error(loc, "atomic counters can only be highp", "atomic_uint", "");
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'");
2271 error(loc, "type requires declaration of default precision qualifier", TType::getBasicString(publicType.basicType), "");
2272 publicType.qualifier.precision = EpqMedium;
2273 defaultPrecision[publicType.basicType] = EpqMedium;
2275 } else if (publicType.qualifier.precision != EpqNone)
2276 error(loc, "type cannot have precision qualifier", TType::getBasicString(publicType.basicType), "");
2279 void TParseContext::parameterTypeCheck(TSourceLoc loc, TStorageQualifier qualifier, const TType& type)
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(), "");
2285 bool TParseContext::containsFieldWithBasicType(const TType& type, TBasicType basicType)
2287 if (type.getBasicType() == basicType)
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))
2302 // Do size checking for an array type's size.
2304 void TParseContext::arraySizeCheck(TSourceLoc loc, TIntermTyped* expr, int& size)
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", "", "");
2314 size = constant->getConstArray()[0].getIConst();
2317 error(loc, "array size must be a positive integer", "", "");
2325 // See if this qualifier can be an array.
2327 // Returns true if there is an error.
2329 bool TParseContext::arrayQualifierError(TSourceLoc loc, const TQualifier& qualifier)
2331 if (qualifier.storage == EvqConst) {
2332 profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "const array");
2333 profileRequires(loc, EEsProfile, 300, 0, "const array");
2336 if (qualifier.storage == EvqVaryingIn && language == EShLangVertex) {
2337 requireProfile(loc, ~EEsProfile, "vertex input arrays");
2338 profileRequires(loc, ENoProfile, 150, 0, "vertex input arrays");
2345 // Require array to have size
2347 void TParseContext::arraySizeRequiredCheck(TSourceLoc loc, int size)
2350 error(loc, "array size required", "", "");
2355 void TParseContext::structArrayCheck(TSourceLoc loc, TType* type)
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);
2365 void TParseContext::arrayDimError(TSourceLoc loc)
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");
2372 void TParseContext::arrayDimCheck(TSourceLoc loc, TArraySizes* sizes1, TArraySizes* sizes2)
2374 if ((sizes1 && sizes2) ||
2375 (sizes1 && sizes1->isArrayOfArrays()) ||
2376 (sizes2 && sizes2->isArrayOfArrays()))
2380 void TParseContext::arrayDimCheck(TSourceLoc loc, const TType* type, TArraySizes* sizes2)
2382 if ((type && type->isArray() && sizes2) ||
2383 (sizes2 && sizes2->isArrayOfArrays()))
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.
2391 // size == 0 means no specified size.
2393 void TParseContext::declareArray(TSourceLoc loc, TString& identifier, const TType& type, TSymbol*& symbol, bool& newDeclaration)
2397 symbol = symbolTable.find(identifier, 0, ¤tScope);
2399 if (symbol && builtInName(identifier) && ! symbolTable.atBuiltInLevel()) {
2400 // bad shader (errors already reported) trying to redeclare a built-in name as an array
2403 if (symbol == 0 || ! currentScope) {
2405 // Successfully process a new definition.
2406 // (Redeclarations have to take place at the same scope; otherwise they are hiding declarations)
2408 symbol = new TVariable(&identifier, type);
2409 symbolTable.insert(*symbol);
2410 newDeclaration = true;
2412 if (! symbolTable.atBuiltInLevel()) {
2413 if (isIoResizeArray(type)) {
2414 ioArraySymbolResizeList.push_back(symbol);
2415 checkIoArraysConsistency(loc, true);
2417 fixIoArraySize(loc, symbol->getWritableType());
2422 if (symbol->getAsAnonMember()) {
2423 error(loc, "cannot redeclare a user-block member array", identifier.c_str(), "");
2430 // Process a redeclaration.
2434 error(loc, "array variable name expected", identifier.c_str(), "");
2438 // redeclareBuiltinVariable() should have already done the copyUp()
2439 TType& existingType = symbol->getWritableType();
2441 if (! existingType.isArray()) {
2442 error(loc, "redeclaring non-array as array", identifier.c_str(), "");
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(), "");
2452 if (! existingType.sameElementType(type)) {
2453 error(loc, "redeclaration of array with a different type", identifier.c_str(), "");
2457 arrayLimitCheck(loc, identifier, type.getArraySize());
2459 existingType.updateArraySizes(type);
2461 if (isIoResizeArray(type))
2462 checkIoArraysConsistency(loc);
2465 void TParseContext::updateImplicitArraySize(TSourceLoc loc, TIntermNode *node, int index)
2467 // maybe there is nothing to do...
2468 TIntermTyped* typedNode = node->getAsTyped();
2469 if (typedNode->getType().getImplicitArraySize() > index)
2472 // something to do...
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)
2488 blockIndex = deref->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
2490 lookupName = &deref->getLeft()->getAsSymbolNode()->getName();
2491 if (IsAnonymous(*lookupName))
2492 lookupName = &(*deref->getLeft()->getType().getStruct())[blockIndex].type->getFieldName();
2495 // Lookup the symbol, should only fail if shader code is incorrect
2496 symbol = symbolTable.find(*lookupName);
2500 if (symbol->getAsFunction()) {
2501 error(loc, "array variable name expected", symbol->getName().c_str(), "");
2505 symbol->getWritableType().setImplicitArraySize(index + 1);
2509 // Enforce non-initializer type/qualifier rules.
2511 void TParseContext::nonInitConstCheck(TSourceLoc loc, TString& identifier, TType& type)
2514 // Make the qualifier make sense, given that there is an initializer.
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(), "");
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.
2528 // Returns 0 if no redeclaration took place; meaning a normal declaration still
2529 // needs to occur for it, not necessarily an error.
2531 // Returns a redeclared and type-modified variable if a redeclarated occurred.
2533 TSymbol* TParseContext::redeclareBuiltinVariable(TSourceLoc loc, const TString& identifier, const TQualifier& qualifier, const TShaderQualifiers& publicType, bool& newDeclaration)
2535 if (profile == EEsProfile || ! builtInName(identifier) || symbolTable.atBuiltInLevel() || ! symbolTable.atGlobalLevel())
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")
2548 // Potentially redeclaring a built-in variable...
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") {
2562 // Find the existing symbol, if any.
2564 TSymbol* symbol = symbolTable.find(identifier, &builtIn);
2566 // If the symbol was not found, this must be a version/profile/stage
2567 // that doesn't have it.
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.
2575 // Copy the symbol up to make a writable version
2576 makeEditable(symbol);
2577 newDeclaration = true;
2580 // Now, modify the type of the copy, as per the type of the current redeclaration.
2582 TQualifier& symbolQualifier = symbol->getWritableType().getQualifier();
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());
2641 // TODO: semantics quality: separate smooth from nothing declared, then use IsInterpolation for several tests above
2650 // Either redeclare the requested block, or give an error message why it can't be done.
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)
2655 const char* feature = "built-in block redeclaration";
2656 requireProfile(loc, ~EEsProfile, feature);
2657 profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
2659 if (blockName != "gl_PerVertex" && blockName != "gl_PerFragment") {
2660 error(loc, "cannot redeclare block: ", "block declaration", blockName.c_str());
2664 // Redeclaring a built-in block...
2666 if (instanceName && ! builtInName(*instanceName)) {
2667 error(loc, "cannot redeclare a built-in block with a user name", instanceName->c_str(), "");
2671 // Blocks with instance names are easy to find, lookup the instance name,
2672 // Anonymous blocks need to be found via a member.
2676 block = symbolTable.find(*instanceName, &builtIn);
2678 block = symbolTable.find(newTypeList.front().type->getFieldName(), &builtIn);
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();
2684 error(loc, "no declaration found for redeclaration", errorName, "");
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.
2690 error(loc, "can only redeclare a built-in block once, and before any use", blockName.c_str(), "");
2694 // Copy the block to make a writable version, to insert into the block table after editing.
2695 block = symbolTable.copyUpDeferredInsert(block);
2697 if (block->getType().getBasicType() != EbtBlock) {
2698 error(loc, "cannot redeclare a non block as a block", errorName, "");
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()) {
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()) {
2716 memberLoc = newMember->loc;
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;
2749 // go to next member
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.
2756 member = type.getWritableStruct()->erase(member);
2758 member->type->hideMember();
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());
2777 symbolTable.insert(*block);
2779 // Check for general layout qualifier errors
2780 layoutObjectCheck(loc, *block);
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());
2789 // Save it in the AST for linker use.
2790 intermediate.addSymbolLinkageNode(linkage, *block);
2793 void TParseContext::paramCheckFix(TSourceLoc loc, const TStorageQualifier& qualifier, TType& type)
2795 switch (qualifier) {
2797 case EvqConstReadOnly:
2798 type.getQualifier().storage = EvqConstReadOnly;
2803 type.getQualifier().storage = qualifier;
2806 type.getQualifier().storage = EvqIn;
2809 type.getQualifier().storage = EvqIn;
2810 error(loc, "storage qualifier not allowed on function parameter", GetStorageQualifierString(qualifier), "");
2815 void TParseContext::paramCheckFix(TSourceLoc loc, const TQualifier& qualifier, TType& type)
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;
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", "", "");
2832 paramCheckFix(loc, qualifier.storage, type);
2835 void TParseContext::nestedBlockCheck(TSourceLoc loc)
2837 if (structNestingLevel > 0)
2838 error(loc, "cannot nest a block definition inside a structure or block", "", "");
2839 ++structNestingLevel;
2842 void TParseContext::nestedStructCheck(TSourceLoc loc)
2844 if (structNestingLevel > 0)
2845 error(loc, "cannot nest a structure definition inside a structure or block", "", "");
2846 ++structNestingLevel;
2849 void TParseContext::arrayObjectCheck(TSourceLoc loc, const TType& type, const char* op)
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);
2858 void TParseContext::opaqueCheck(TSourceLoc loc, const TType& type, const char* op)
2860 if (containsFieldWithBasicType(type, EbtSampler))
2861 error(loc, "can't use with samplers or structs containing samplers", op, "");
2864 void TParseContext::structTypeCheck(TSourceLoc loc, TPublicType& publicType)
2866 const TTypeList& typeList = *publicType.userDef->getStruct();
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();
2882 if (memberQualifier.invariant)
2883 error(memberLoc, "cannot use invariant qualifier on structure members", typeList[member].type->getFieldName().c_str(), "");
2888 // See if this loop satisfies the limitations for ES 2.0 (version 100) for loops in Appendex A:
2890 // "The loop index has type int or float.
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:
2900 // loop-index += constant-expression
2901 // loop-index -= constant-expression
2903 // The body is handled in an AST traversal.
2905 void TParseContext::inductiveLoopCheck(TSourceLoc loc, TIntermNode* init, TIntermLoop* loop)
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)
2911 TIntermBinary* binaryInit;
2913 // get the declaration assignment
2914 binaryInit = init->getAsAggregate()->getSequence()[0]->getAsBinaryNode();
2919 error(loc, "inductive-loop init-declaration requires the form \"type-specifier loop-index = constant-expression\"", "limitations", "");
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", "");
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", "");
2935 // get the unique id of the loop index
2936 int loopIndex = binaryInit->getLeft()->getAsSymbolNode()->getId();
2937 inductiveLoopIds.insert(loopIndex);
2939 // condition's form must be "loop-index relational-operator constant-expression"
2940 bool badCond = ! loop->getTest();
2942 TIntermBinary* binaryCond = loop->getTest()->getAsBinaryNode();
2943 badCond = ! binaryCond;
2945 switch (binaryCond->getOp()) {
2946 case EOpGreaterThan:
2947 case EOpGreaterThanEqual:
2949 case EOpLessThanEqual:
2957 if (binaryCond && (! binaryCond->getLeft()->getAsSymbolNode() ||
2958 binaryCond->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
2959 ! binaryCond->getRight()->getAsConstantUnion()))
2963 error(loc, "inductive-loop condition requires the form \"loop-index <comparison-op> constant-expression\"", "limitations", "");
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:
2987 if (binaryTerminal && (! binaryTerminal->getLeft()->getAsSymbolNode() ||
2988 binaryTerminal->getLeft()->getAsSymbolNode()->getId() != loopIndex ||
2989 ! binaryTerminal->getRight()->getAsConstantUnion()))
2991 if (unaryTerminal && (! unaryTerminal->getOperand()->getAsSymbolNode() ||
2992 unaryTerminal->getOperand()->getAsSymbolNode()->getId() != loopIndex))
2996 error(loc, "inductive-loop termination requires the form \"loop-index++, loop-index--, loop-index += constant-expression, or loop-index -= constant-expression\"", "limitations", "");
3001 inductiveLoopBodyCheck(loop->getBody(), loopIndex, symbolTable);
3004 // Do limit checks against for all built-in arrays.
3005 void TParseContext::arrayLimitCheck(TSourceLoc loc, const TString& identifier, int size)
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");
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)
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());
3026 // Do any additional error checking, etc., once we know the parsing is done.
3028 void TParseContext::finalErrorCheck()
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]);
3036 // Layout qualifier stuff.
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)
3043 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
3045 if (id == TQualifier::getLayoutMatrixString(ElmColumnMajor)) {
3046 publicType.qualifier.layoutMatrix = ElmColumnMajor;
3049 if (id == TQualifier::getLayoutMatrixString(ElmRowMajor)) {
3050 publicType.qualifier.layoutMatrix = ElmRowMajor;
3053 if (id == TQualifier::getLayoutPackingString(ElpPacked)) {
3054 publicType.qualifier.layoutPacking = ElpPacked;
3057 if (id == TQualifier::getLayoutPackingString(ElpShared)) {
3058 publicType.qualifier.layoutPacking = ElpShared;
3061 if (id == TQualifier::getLayoutPackingString(ElpStd140)) {
3062 publicType.qualifier.layoutPacking = ElpStd140;
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;
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;
3084 if (language == EShLangGeometry || language == EShLangTessEvaluation) {
3085 if (id == TQualifier::getGeometryString(ElgTriangles)) {
3086 publicType.shaderQualifiers.geometry = ElgTriangles;
3089 if (language == EShLangGeometry) {
3090 if (id == TQualifier::getGeometryString(ElgPoints)) {
3091 publicType.shaderQualifiers.geometry = ElgPoints;
3094 if (id == TQualifier::getGeometryString(ElgLineStrip)) {
3095 publicType.shaderQualifiers.geometry = ElgLineStrip;
3098 if (id == TQualifier::getGeometryString(ElgLines)) {
3099 publicType.shaderQualifiers.geometry = ElgLines;
3102 if (id == TQualifier::getGeometryString(ElgLinesAdjacency)) {
3103 publicType.shaderQualifiers.geometry = ElgLinesAdjacency;
3106 if (id == TQualifier::getGeometryString(ElgTrianglesAdjacency)) {
3107 publicType.shaderQualifiers.geometry = ElgTrianglesAdjacency;
3110 if (id == TQualifier::getGeometryString(ElgTriangleStrip)) {
3111 publicType.shaderQualifiers.geometry = ElgTriangleStrip;
3115 assert(language == EShLangTessEvaluation);
3118 if (id == TQualifier::getGeometryString(ElgTriangles)) {
3119 publicType.shaderQualifiers.geometry = ElgTriangles;
3122 if (id == TQualifier::getGeometryString(ElgQuads)) {
3123 publicType.shaderQualifiers.geometry = ElgQuads;
3126 if (id == TQualifier::getGeometryString(ElgIsolines)) {
3127 publicType.shaderQualifiers.geometry = ElgIsolines;
3132 if (id == TQualifier::getVertexSpacingString(EvsEqual)) {
3133 publicType.shaderQualifiers.spacing = EvsEqual;
3136 if (id == TQualifier::getVertexSpacingString(EvsFractionalEven)) {
3137 publicType.shaderQualifiers.spacing = EvsFractionalEven;
3140 if (id == TQualifier::getVertexSpacingString(EvsFractionalOdd)) {
3141 publicType.shaderQualifiers.spacing = EvsFractionalOdd;
3146 if (id == TQualifier::getVertexOrderString(EvoCw)) {
3147 publicType.shaderQualifiers.order = EvoCw;
3150 if (id == TQualifier::getVertexOrderString(EvoCcw)) {
3151 publicType.shaderQualifiers.order = EvoCcw;
3156 if (id == "point_mode") {
3157 publicType.shaderQualifiers.pointMode = true;
3162 if (language == EShLangFragment) {
3163 if (id == "origin_upper_left") {
3164 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "origin_upper_left");
3165 publicType.shaderQualifiers.originUpperLeft = true;
3168 if (id == "pixel_center_integer") {
3169 requireProfile(loc, ECoreProfile | ECompatibilityProfile, "pixel_center_integer");
3170 publicType.shaderQualifiers.pixelCenterInteger = true;
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;
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;
3188 error(loc, "unrecognized layout identifier, or qualifier requires assignment (e.g., binding = 4)", id.c_str(), "");
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)
3195 const char* feature = "layout-id value";
3196 const char* nonLiteralFeature = "non-literal layout-id value";
3198 integerCheck(node, feature);
3199 const TIntermConstantUnion* constUnion = node->getAsConstantUnion();
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);
3208 // grammar should have give out the error message
3213 error(loc, "cannot be negative", feature, "");
3217 std::transform(id.begin(), id.end(), id.begin(), ::tolower);
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;
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", "");
3235 publicType.qualifier.layoutAlign = value;
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(), "");
3244 publicType.qualifier.layoutLocation = value;
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(), "");
3252 publicType.qualifier.layoutBinding = value;
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(), "");
3260 publicType.qualifier.layoutComponent = value;
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
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);
3280 publicType.qualifier.layoutXfbBuffer = value;
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);
3286 publicType.qualifier.layoutXfbOffset = value;
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;
3305 case EShLangTessControl:
3306 if (id == "vertices") {
3307 publicType.shaderQualifiers.vertices = value;
3312 case EShLangTessEvaluation:
3315 case EShLangGeometry:
3316 if (id == "invocations") {
3317 profileRequires(loc, ECompatibilityProfile | ECoreProfile, 400, 0, "invocations");
3318 publicType.shaderQualifiers.invocations = value;
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", "");
3327 if (id == "stream") {
3328 publicType.qualifier.layoutStream = value;
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;
3343 case EShLangCompute:
3344 if (id == "local_size_x") {
3345 publicType.shaderQualifiers.localSize[0] = value;
3348 if (id == "local_size_y") {
3349 publicType.shaderQualifiers.localSize[1] = value;
3352 if (id == "local_size_z") {
3353 publicType.shaderQualifiers.localSize[2] = value;
3362 error(loc, "there is no such layout identifier for this stage taking an assigned value", id.c_str(), "");
3365 // Merge any layout qualifier information from src into dst, leaving everything else in dst alone
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."
3380 void TParseContext::mergeObjectLayoutQualifiers(TSourceLoc loc, TQualifier& dst, const TQualifier& src, bool inheritOnly)
3382 if (src.hasMatrix())
3383 dst.layoutMatrix = src.layoutMatrix;
3384 if (src.hasPacking())
3385 dst.layoutPacking = src.layoutPacking;
3387 if (src.hasStream())
3388 dst.layoutStream = src.layoutStream;
3390 if (src.hasFormat())
3391 dst.layoutFormat = src.layoutFormat;
3393 if (src.hasXfbBuffer())
3394 dst.layoutXfbBuffer = src.layoutXfbBuffer;
3397 dst.layoutAlign = src.layoutAlign;
3399 if (! inheritOnly) {
3400 if (src.hasLocation())
3401 dst.layoutLocation = src.layoutLocation;
3402 if (src.hasComponent())
3403 dst.layoutComponent = src.layoutComponent;
3405 dst.layoutIndex = src.layoutIndex;
3407 if (src.hasOffset())
3408 dst.layoutOffset = src.layoutOffset;
3410 if (src.layoutBinding != TQualifier::layoutBindingEnd)
3411 dst.layoutBinding = src.layoutBinding;
3413 if (src.hasXfbStride())
3414 dst.layoutXfbStride = src.layoutXfbStride;
3415 if (src.hasXfbOffset())
3416 dst.layoutXfbOffset = src.layoutXfbOffset;
3420 // Do error layout error checking given a full variable/block declaration.
3421 void TParseContext::layoutObjectCheck(TSourceLoc loc, const TSymbol& symbol)
3423 const TType& type = symbol.getType();
3424 const TQualifier& qualifier = type.getQualifier();
3426 // first, cross check WRT to just the type
3427 layoutTypeCheck(loc, type);
3429 // now, any remaining error checking based on the object itself
3431 if (qualifier.hasAnyLocation()) {
3432 switch (qualifier.storage) {
3435 if (symbol.getAsVariable() == 0)
3436 error(loc, "can only be used on variable declaration", "location", "");
3443 // Check packing and matrix
3444 if (qualifier.hasUniformLayout()) {
3445 switch (qualifier.storage) {
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", "");
3462 // these were already filtered by layoutTypeCheck() (or its callees)
3468 // Do layout error checking with respect to a type.
3469 void TParseContext::layoutTypeCheck(TSourceLoc loc, const TType& type)
3471 const TQualifier& qualifier = type.getQualifier();
3473 // first, intra layout qualifier-only error checking
3474 layoutQualifierCheck(loc, qualifier);
3476 // now, error checking combining type and qualifier
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", "");
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", "");
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", "");
3495 switch (qualifier.storage) {
3498 if (type.getBasicType() == EbtBlock)
3499 profileRequires(loc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, "location qualifier on in/out block");
3505 error(loc, "can only appy to uniform, buffer, in, or out storage qualifiers", "location", "");
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);
3519 if (qualifier.hasXfbOffset() && qualifier.hasXfbBuffer()) {
3520 int repeated = intermediate.addXfbBufferOffset(type);
3522 error(loc, "overlapping offsets at", "xfb_offset", "offset %d in buffer %d", repeated, qualifier.layoutXfbBuffer);
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", "");
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);
3538 if (qualifier.hasBinding()) {
3539 // Binding checking, from the spec:
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
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;
3552 lastBinding += type.getArraySize();
3553 if (lastBinding >= resources.maxCombinedTextureImageUnits)
3554 error(loc, "sampler binding not less than gl_MaxCombinedTextureImageUnits", "binding", type.isArray() ? "(using array)" : "");
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", "");
3565 if (type.getBasicType() == EbtAtomicUint) {
3566 if (! type.getQualifier().hasBinding())
3567 error(loc, "layout(binding=X) is required", "atomic_uint", "");
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", "");
3577 if (qualifier.hasFormat()) {
3578 if (! type.isImage())
3579 error(loc, "only apply to images", TQualifier::getLayoutFormatString(qualifier.layoutFormat), "");
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), "");
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), "");
3597 } else if (type.isImage() && ! qualifier.writeonly)
3598 error(loc, "image variables not declared 'writeonly' must have a format layout qualifier", "", "");
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)
3605 if (qualifier.storage == EvqShared && qualifier.hasLayout())
3606 error(loc, "cannot apply layout qualifiers to a shared variable", "shared", "");
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", "");
3612 if (qualifier.hasAnyLocation()) {
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."
3618 switch (qualifier.storage) {
3621 const char* feature = "location qualifier on input";
3622 if (profile == EEsProfile && version < 310)
3623 requireStage(loc, EShLangVertex, feature);
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);
3631 profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
3632 profileRequires(loc, EEsProfile, 310, 0, feature);
3638 const char* feature = "location qualifier on output";
3639 if (profile == EEsProfile && version < 310)
3640 requireStage(loc, EShLangFragment, feature);
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);
3648 profileRequires(loc, ~EEsProfile, 410, GL_ARB_separate_shader_objects, feature);
3649 profileRequires(loc, EEsProfile, 310, 0, feature);
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);
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", "");
3673 if (qualifier.hasBinding()) {
3674 if (! qualifier.isUniformOrBuffer())
3675 error(loc, "requires uniform or buffer storage qualifier", "binding", "");
3677 if (qualifier.hasStream()) {
3678 if (qualifier.storage != EvqVaryingOut)
3679 error(loc, "can only be used on an output", "stream", "");
3681 if (qualifier.hasXfb()) {
3682 if (qualifier.storage != EvqVaryingOut)
3683 error(loc, "can only be used on an output", "xfb layout qualifier", "");
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", "");
3695 // For places that can't have shader-level layout qualifiers
3696 void TParseContext::checkNoShaderLayouts(TSourceLoc loc, const TShaderQualifiers& shaderQualifiers)
3698 const char* message = "can only apply to a standalone qualifier";
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", "");
3712 for (int i = 0; i < 3; ++i) {
3713 if (shaderQualifiers.localSize[i] > 1)
3714 error(loc, message, "local_size", "");
3718 // Correct and/or advance an object's offset layout qualifier.
3719 void TParseContext::fixOffset(TSourceLoc loc, TSymbol& symbol)
3721 const TQualifier& qualifier = symbol.getType().getQualifier();
3722 if (symbol.getType().getBasicType() == EbtAtomicUint) {
3723 if (qualifier.hasBinding() && (int)qualifier.layoutBinding < resources.maxAtomicCounterBindings) {
3727 if (qualifier.hasOffset())
3728 offset = qualifier.layoutOffset;
3730 offset = atomicUintOffsets[qualifier.layoutBinding];
3731 symbol.getWritableType().getQualifier().layoutOffset = offset;
3733 // Check for overlap
3735 if (symbol.getType().isArray())
3736 numOffsets *= symbol.getType().getArraySize();
3737 int repeated = intermediate.addUsedOffsets(qualifier.layoutBinding, offset, numOffsets);
3739 error(loc, "atomic counters sharing the same offset:", "offset", "%d", repeated);
3741 // Bump the default offset
3742 atomicUintOffsets[qualifier.layoutBinding] = offset + numOffsets;
3748 // Look up a function name in the symbol table, and make sure it is a function.
3750 // Return the function symbol if found, otherwise 0.
3752 const TFunction* TParseContext::findFunction(TSourceLoc loc, const TFunction& call, bool& builtIn)
3754 const TFunction* function = 0;
3756 if (symbolTable.isFunctionNameVariable(call.getName())) {
3757 error(loc, "can't use function syntax on variable", call.getName().c_str(), "");
3761 if (profile == EEsProfile || version < 120)
3762 function = findFunctionExact(loc, call, builtIn);
3763 else if (version < 400)
3764 function = findFunction120(loc, call, builtIn);
3766 function = findFunction400(loc, call, builtIn);
3771 // Function finding algorithm for ES and desktop 110.
3772 const TFunction* TParseContext::findFunctionExact(TSourceLoc loc, const TFunction& call, bool& builtIn)
3774 const TFunction* function = 0;
3776 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
3778 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
3783 return symbol->getAsFunction();
3786 // Function finding algorithm for desktop versions 120 through 330.
3787 const TFunction* TParseContext::findFunction120(TSourceLoc loc, const TFunction& call, bool& builtIn)
3789 // first, look for an exact match
3790 TSymbol* symbol = symbolTable.find(call.getMangledName(), &builtIn);
3792 return symbol->getAsFunction();
3794 // exact match not found, look through a list of overloaded functions of the same name
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."
3803 const TFunction* candidate = 0;
3804 TVector<TFunction*> candidateList;
3805 symbolTable.findFunctionNameList(call.getMangledName(), candidateList, builtIn);
3807 int numPossibleMatches = 0;
3808 for (TVector<TFunction*>::const_iterator it = candidateList.begin(); it != candidateList.end(); ++it) {
3809 const TFunction& function = *(*it);
3811 // to even be a potential match, number of arguments has to match
3812 if (call.getParamCount() != function.getParamCount())
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)
3821 // We have a mismatch in type, see if it is implicitly convertible
3823 if (function[i].type->isArray() || call[i].type->isArray() ||
3824 ! function[i].type->sameElementShape(*call[i].type))
3825 possibleMatch = false;
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;
3832 if (function[i].type->getQualifier().isParamOutput()) {
3833 if (! intermediate.canImplicitlyPromote(function[i].type->getBasicType(), call[i].type->getBasicType()))
3834 possibleMatch = false;
3837 if (! possibleMatch)
3840 if (possibleMatch) {
3842 // our second match, meaning ambiguity
3843 error(loc, "ambiguous function signature match: multiple signatures match under implicit type conversion", call.getName().c_str(), "");
3845 candidate = &function;
3850 error(loc, "no matching overloaded function found", call.getName().c_str(), "");
3855 // Function finding algorithm for desktop version 400 and above.
3856 const TFunction* TParseContext::findFunction400(TSourceLoc loc, const TFunction& call, bool& builtIn)
3858 // TODO: 4.00 functionality: findFunction400()
3859 return findFunction120(loc, call, builtIn);
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)
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", "");
3871 atomicUintOffsets[publicType.qualifier.layoutBinding] = publicType.qualifier.layoutOffset;
3875 if (publicType.qualifier.hasLayout())
3876 warn(loc, "useless application of layout qualifier", "layout", "");
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.
3884 // Returns a subtree node that computes an initializer, if needed.
3885 // Returns 0 if there is no code to execute for initialization.
3887 TIntermNode* TParseContext::declareVariable(TSourceLoc loc, TString& identifier, const TPublicType& publicType, TArraySizes* arraySizes, TIntermTyped* initializer)
3889 TType type(publicType);
3891 if (voidErrorCheck(loc, identifier, type.getBasicType()))
3895 rValueErrorCheck(loc, "initializer", initializer);
3897 nonInitConstCheck(loc, identifier, type);
3899 invariantCheck(loc, type, identifier);
3900 samplerCheck(loc, type, identifier);
3901 atomicUintCheck(loc, type, identifier);
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", "");
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);
3912 reservedErrorCheck(loc, identifier);
3914 inheritGlobalDefaults(type.getQualifier());
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);
3924 type.setArraySizes(arraySizes);
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());
3930 if (! arrayQualifierError(loc, type.getQualifier()))
3931 declareArray(loc, identifier, type, symbol, newDeclaration);
3934 profileRequires(loc, ENoProfile, 120, GL_3DL_array_objects, "initializer");
3935 profileRequires(loc, EEsProfile, 300, 0, "initializer");
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());
3948 // Deal with initializer
3949 TIntermNode* initNode = 0;
3950 if (symbol && initializer) {
3951 TVariable* variable = symbol->getAsVariable();
3953 error(loc, "initializer requires a variable, not a member", identifier.c_str(), "");
3956 initNode = executeInitializer(loc, identifier, initializer, variable);
3959 // look for errors in layout qualifier use
3960 layoutObjectCheck(loc, *symbol);
3961 fixOffset(loc, *symbol);
3963 // see if it's a linker-level object to track
3964 if (newDeclaration && symbolTable.atGlobalLevel())
3965 intermediate.addSymbolLinkageNode(linkage, *symbol);
3970 // Pick up global defaults from the provide global defaults into dst.
3971 void TParseContext::inheritGlobalDefaults(TQualifier& dst) const
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;
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.
3987 TVariable* TParseContext::makeInternalVariable(const char* name, const TType& type) const
3989 TString* nameString = new TString(name);
3990 TSourceLoc loc = {0, 0};
3991 TVariable* variable = new TVariable(nameString, type);
3992 symbolTable.makeInternalVariable(*variable);
3998 // Declare a non-array variable, the main point being there is no redeclaration
3999 // for resizing allowed.
4001 // Return the successfully declared variable.
4003 TVariable* TParseContext::declareNonArray(TSourceLoc loc, TString& identifier, TType& type, bool& newDeclaration)
4005 // make a new variable
4006 TVariable* variable = new TVariable(&identifier, type);
4008 ioArrayCheck(loc, type, identifier);
4009 // add variable to symbol table
4010 if (! symbolTable.insert(*variable)) {
4011 error(loc, "redefinition", variable->getName().c_str(), "");
4014 newDeclaration = true;
4020 // Handle all types of initializers from the grammar.
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.
4025 TIntermNode* TParseContext::executeInitializer(TSourceLoc loc, TString& identifier,
4026 TIntermTyped* initializer, TVariable* variable)
4029 // Identifier must be of type constant, a global, or a temporary, and
4030 // starting at version 120, desktop allows uniforms to have initializers.
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(), "");
4038 arrayObjectCheck(loc, variable->getType(), "array initializer");
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.
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;
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());
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;
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;
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;
4081 if (qualifier == EvqConst || qualifier == EvqUniform) {
4082 // Compile-time tagging of the variable with it's constant value...
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;
4092 variable->setConstArray(initializer->getAsConstantUnion()->getConstArray());
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);
4098 assignError(loc, "=", intermSymbol->getCompleteString(), initializer->getCompleteString());
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
4113 TIntermTyped* TParseContext::convertInitializerList(TSourceLoc loc, const TType& type, TIntermTyped* initializer)
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.
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)
4124 // Of the initializer-list set of nodes, need to process bottom up,
4125 // so recurse deep, then process on the way up.
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.
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)
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", "");
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)
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());
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)
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());
4170 error(loc, "unexpected initializer-list type:", "initializer list", type.getCompleteString().c_str());
4174 // now that the subtree is processed, process this node
4175 return addConstructor(loc, initList, type, mapTypeToConstructorOp(type));
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.
4182 // Returns 0 for an error or the constructed node (aggregate or typed) for no error.
4184 TIntermTyped* TParseContext::addConstructor(TSourceLoc loc, TIntermNode* node, const TType& type, TOperator op)
4186 if (node == 0 || node->getAsTyped() == 0)
4188 rValueErrorCheck(loc, "constructor", node->getAsTyped());
4190 TIntermAggregate* aggrNode = node->getAsAggregate();
4192 TTypeList::const_iterator memberTypes;
4193 if (op == EOpConstructStruct)
4194 memberTypes = type.getStruct()->begin();
4197 elementType.shallowCopy(type);
4199 elementType.dereference();
4203 if (aggrNode->getOp() != EOpNull || aggrNode->getSequence().size() == 1)
4210 TIntermTyped *newNode;
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.
4215 newNode = constructStruct(node, elementType, 1, node->getLoc());
4216 else if (op == EOpConstructStruct)
4217 newNode = constructStruct(node, *(*memberTypes).type, 1, node->getLoc());
4219 newNode = constructBuiltIn(type, op, node->getAsTyped(), node->getLoc(), false);
4221 if (newNode && (type.isArray() || op == EOpConstructStruct))
4222 newNode = intermediate.setAggregateOperator(newNode, EOpConstructStruct, type, loc);
4228 // Handle list of arguments.
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
4234 int paramCount = 0; // keeps a track of the constructor parameter number being checked
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.
4240 for (TIntermSequence::iterator p = sequenceVector.begin();
4241 p != sequenceVector.end(); p++, paramCount++) {
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());
4247 newNode = constructBuiltIn(type, op, (*p)->getAsTyped(), node->getLoc(), true);
4255 TIntermTyped* constructor = intermediate.setAggregateOperator(aggrNode, op, type, loc);
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.
4265 // Returns 0 for an error or the constructed node.
4267 TIntermTyped* TParseContext::constructBuiltIn(const TType& type, TOperator op, TIntermTyped* node, TSourceLoc loc, bool subset)
4269 TIntermTyped* newNode;
4273 // First, convert types as needed.
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;
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;
4308 case EOpConstructIVec2:
4309 case EOpConstructIVec3:
4310 case EOpConstructIVec4:
4311 case EOpConstructInt:
4312 basicOp = EOpConstructInt;
4315 case EOpConstructUVec2:
4316 case EOpConstructUVec3:
4317 case EOpConstructUVec4:
4318 case EOpConstructUint:
4319 basicOp = EOpConstructUint;
4322 case EOpConstructBVec2:
4323 case EOpConstructBVec3:
4324 case EOpConstructBVec4:
4325 case EOpConstructBool:
4326 basicOp = EOpConstructBool;
4330 error(loc, "unsupported construction", "", "");
4334 newNode = intermediate.addUnaryMath(basicOp, node, node->getLoc());
4336 error(loc, "can't convert", "constructor", "");
4341 // Now, if there still isn't an operation to do the construction, and we need one, add one.
4344 // Otherwise, skip out early.
4345 if (subset || (newNode != node && newNode->getType() == type))
4348 // setAggregateOperator will insert a new node for the constructor, as needed.
4349 return intermediate.setAggregateOperator(newNode, op, type, loc);
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.
4355 // Returns 0 for an error or the input node itself if the expected and the given parameter types match.
4357 TIntermTyped* TParseContext::constructStruct(TIntermNode* node, const TType& type, int paramCount, TSourceLoc loc)
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());
4371 // Do everything needed to add an interface block.
4373 void TParseContext::declareBlock(TSourceLoc loc, TTypeList& typeList, const TString* instanceName, TArraySizes* arraySizes)
4375 if (profile == EEsProfile && arraySizes)
4376 arraySizeRequiredCheck(loc, arraySizes->getSize());
4378 switch (currentBlockQualifier.storage) {
4380 profileRequires(loc, EEsProfile, 300, 0, "uniform block");
4381 profileRequires(loc, ENoProfile, 140, 0, "uniform block");
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");
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", "");
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", "");
4401 error(loc, "only uniform, buffer, in, or out blocks are supported", blockName->c_str(), "");
4405 arrayDimCheck(loc, arraySizes, 0);
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");
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(), "");
4432 // This might be a redeclaration of a built-in block. If so, redeclareBuiltinBlock() will
4434 if (! symbolTable.atBuiltInLevel() && builtInName(*blockName)) {
4435 redeclareBuiltinBlock(loc, typeList, *blockName, instanceName, arraySizes);
4439 // Not a redeclaration of a built-in; check that all names are user names.
4440 reservedErrorCheck(loc, *blockName);
4442 reservedErrorCheck(loc, *instanceName);
4443 for (unsigned int member = 0; member < typeList.size(); ++member)
4444 reservedErrorCheck(typeList[member].loc, typeList[member].type->getFieldName());
4446 // Make default block qualification, and adjust the member qualifications
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;
4457 // fix and check for member layout qualifiers
4459 mergeObjectLayoutQualifiers(loc, defaultQualification, currentBlockQualifier, true);
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;
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", "");
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", "");
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) {
4496 requireProfile(memberLoc, ECoreProfile | ECompatibilityProfile, feature);
4497 profileRequires(memberLoc, ECoreProfile | ECompatibilityProfile, 440, GL_ARB_enhanced_layouts, feature);
4498 memberWithLocation = true;
4501 error(memberLoc, "can only use in an in/out block", feature, "");
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", "");
4511 TQualifier newMemberQualification = defaultQualification;
4512 mergeQualifiers(memberLoc, newMemberQualification, memberQualifier, false);
4513 memberQualifier = newMemberQualification;
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);
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);
4528 // Build and add the interface block as a new type named 'blockName'
4531 TType blockType(&typeList, *blockName, currentBlockQualifier);
4533 blockType.setArraySizes(arraySizes);
4535 ioArrayCheck(loc, blockType, instanceName ? *instanceName : *blockName);
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.
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)."
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.
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());
4560 error(loc, "block name cannot redefine a non-block name", blockName->c_str(), "");
4565 // Add the variable, as anonymous or named instanceName.
4566 // Make an anonymous variable if no name was provided.
4568 instanceName = NewPoolTString("");
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(), "");
4575 error(loc, "block instance name redefinition", variable.getName().c_str(), "");
4580 // Check for general layout qualifier errors
4581 layoutObjectCheck(loc, variable);
4583 if (isIoResizeArray(blockType)) {
4584 ioArraySymbolResizeList.push_back(&variable);
4585 checkIoArraysConsistency(loc, true);
4587 fixIoArraySize(loc, variable.getWritableType());
4589 // Save it in the AST for linker use.
4590 intermediate.addSymbolLinkageNode(linkage, variable);
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)
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", "");
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", "");
4617 if (qualifier.hasIndex()) {
4618 error(loc, "cannot apply to a block", "index", "");
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;
4630 nextLocation = memberQualifier.layoutLocation + intermediate.computeTypeLocationSize(*typeList[member].type);
4636 void TParseContext::fixBlockXfbOffsets(TSourceLoc loc, TQualifier& qualifier, TTypeList& typeList)
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
4643 if (! qualifier.hasXfbBuffer() || ! qualifier.hasXfbOffset())
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"
4655 RoundToPow2(nextOffset, 8);
4656 memberQualifier.layoutXfbOffset = nextOffset;
4658 nextOffset = memberQualifier.layoutXfbOffset;
4659 nextOffset += memberSize;
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;
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.
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.
4673 void TParseContext::fixBlockUniformOffsets(TSourceLoc loc, TQualifier& qualifier, TTypeList& typeList)
4675 if (! qualifier.isUniformOrBuffer())
4677 if (qualifier.layoutPacking != ElpStd140 && qualifier.layoutPacking != ElpStd430)
4682 for (unsigned int member = 0; member < typeList.size(); ++member) {
4683 TQualifier& memberQualifier = typeList[member].type->getQualifier();
4684 TSourceLoc memberLoc = typeList[member].loc;
4686 // "When align is applied to an array, it effects only the start of the array, not the array's internal stride."
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", "");
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", "");
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);
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);
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;
4721 // For an identifier that is already declared, add more qualification to it.
4722 void TParseContext::addQualifierToExisting(TSourceLoc loc, TQualifier qualifier, const TString& identifier)
4724 TSymbol* symbol = symbolTable.find(identifier);
4726 error(loc, "identifier not previously declared", identifier.c_str(), "");
4729 if (symbol->getAsFunction()) {
4730 error(loc, "cannot re-qualify a function name", identifier.c_str(), "");
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(), "");
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);
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);
4755 warn(loc, "unknown requalification", "", "");
4758 void TParseContext::addQualifierToExisting(TSourceLoc loc, TQualifier qualifier, TIdentifierList& identifiers)
4760 for (unsigned int i = 0; i < identifiers.size(); ++i)
4761 addQualifierToExisting(loc, qualifier, *identifiers[i]);
4764 void TParseContext::invariantCheck(TSourceLoc loc, const TType& type, const TString& identifier)
4766 if (! type.getQualifier().invariant)
4769 bool pipeOut = type.getQualifier().isPipeOutput();
4770 bool pipeIn = type.getQualifier().isPipeInput();
4771 if (version >= 300 || profile != EEsProfile && version >= 420) {
4773 error(loc, "can only apply to an output:", "invariant", identifier.c_str());
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", "");
4781 // Updating default qualifier for the case of a declaration with just a qualifier,
4782 // no type, block, or identifier.
4784 void TParseContext::updateStandaloneQualifierDefaults(TSourceLoc loc, const TPublicType& publicType)
4786 if (publicType.shaderQualifiers.vertices) {
4787 assert(language == EShLangTessControl || language == EShLangGeometry);
4788 const char* id = (language == EShLangTessControl) ? "vertices" : "max_vertices";
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, "");
4795 if (language == EShLangTessControl)
4796 checkIoArraysConsistency(loc);
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", "");
4804 if (publicType.shaderQualifiers.geometry != ElgNone) {
4805 if (publicType.qualifier.storage == EvqVaryingIn) {
4806 switch (publicType.shaderQualifiers.geometry) {
4809 case ElgLinesAdjacency:
4811 case ElgTrianglesAdjacency:
4814 if (intermediate.setInputPrimitive(publicType.shaderQualifiers.geometry)) {
4815 if (language == EShLangGeometry)
4816 checkIoArraysConsistency(loc);
4818 error(loc, "cannot change previously set input primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
4821 error(loc, "cannot apply to input", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
4823 } else if (publicType.qualifier.storage == EvqVaryingOut) {
4824 switch (publicType.shaderQualifiers.geometry) {
4827 case ElgTriangleStrip:
4828 if (! intermediate.setOutputPrimitive(publicType.shaderQualifiers.geometry))
4829 error(loc, "cannot change previously set output primitive", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
4832 error(loc, "cannot apply to 'out'", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), "");
4835 error(loc, "cannot apply to:", TQualifier::getGeometryString(publicType.shaderQualifiers.geometry), GetStorageQualifierString(publicType.qualifier.storage));
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), "");
4842 error(loc, "can only apply to 'in'", TQualifier::getVertexSpacingString(publicType.shaderQualifiers.spacing), "");
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), "");
4849 error(loc, "can only apply to 'in'", TQualifier::getVertexOrderString(publicType.shaderQualifiers.order), "");
4851 if (publicType.shaderQualifiers.pointMode) {
4852 if (publicType.qualifier.storage == EvqVaryingIn)
4853 intermediate.setPointMode();
4855 error(loc, "can only apply to 'in'", "point_mode", "");
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", "");
4865 case 0: max = resources.maxComputeWorkGroupSizeX; break;
4866 case 1: max = resources.maxComputeWorkGroupSizeY; break;
4867 case 2: max = resources.maxComputeWorkGroupSizeZ; break;
4870 if (intermediate.getLocalSize(i) > (unsigned int)max)
4871 error(loc, "too large; see gl_MaxComputeWorkGroupSize", "local_size", "");
4873 // Fix the existing constant gl_WorkGroupSize with this new information.
4875 TSymbol* symbol = symbolTable.find("gl_WorkGroupSize", &builtIn);
4877 makeEditable(symbol);
4878 TVariable* workGroupSize = symbol->getAsVariable();
4879 workGroupSize->getWritableConstArray()[i].setUConst(intermediate.getLocalSize(i));
4882 error(loc, "can only apply to 'in'", "local_size", "");
4885 if (publicType.shaderQualifiers.earlyFragmentTests) {
4886 if (publicType.qualifier.storage == EvqVaryingIn)
4887 intermediate.setEarlyFragmentTests();
4889 error(loc, "can only apply to 'in'", "early_fragment_tests", "");
4892 const TQualifier& qualifier = publicType.qualifier;
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", "");
4905 layoutQualifierCheck(loc, qualifier);
4907 switch (qualifier.storage) {
4909 if (qualifier.hasMatrix())
4910 globalUniformDefaults.layoutMatrix = qualifier.layoutMatrix;
4911 if (qualifier.hasPacking())
4912 globalUniformDefaults.layoutPacking = qualifier.layoutPacking;
4915 if (qualifier.hasMatrix())
4916 globalBufferDefaults.layoutMatrix = qualifier.layoutMatrix;
4917 if (qualifier.hasPacking())
4918 globalBufferDefaults.layoutPacking = qualifier.layoutPacking;
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);
4933 error(loc, "default qualifier requires 'uniform', 'buffer', 'in', or 'out' storage qualification", "", "");
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", "");
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
4951 void TParseContext::wrapupSwitchSubsequence(TIntermAggregate* statements, TIntermNode* branchNode)
4953 TIntermSequence* switchSequence = switchSequenceStack.back();
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);
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();
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", "");
4979 switchSequence->push_back(branchNode);
4984 // Turn the top-level node sequence built up of wrapupSwitchSubsequence9)
4985 // into a switch node.
4987 TIntermNode* TParseContext::addSwitch(TSourceLoc loc, TIntermTyped* expression, TIntermAggregate* lastStatements)
4989 profileRequires(loc, EEsProfile, 300, 0, "switch statements");
4990 profileRequires(loc, ENoProfile, 130, 0, "switch statements");
4992 wrapupSwitchSubsequence(lastStatements, 0);
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", "");
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)
5004 if (lastStatements == 0) {
5005 warn(loc, "last case/default label not be followed by statements", "switch", "");
5010 TIntermAggregate* body = new TIntermAggregate(EOpSequence);
5011 body->getSequence() = *switchSequenceStack.back();
5014 TIntermSwitch* switchNode = new TIntermSwitch(expression, body);
5015 switchNode->setLoc(loc);
5020 } // end namespace glslang